with open(url_for('static', filename='bmidata.txt') as f:
the above line causes a syntax error (marked at the 'as'). The code is part of the following:
#app.route('/display')
def display():
page_info = {
'title':'Assignment Flask',
'heading': 'Python Flask Assignment'
}
filedata = []
with open(url_for('static', filename='bmidata.txt') as f:
for line in f:
str = line
dataarray = str.split(',')
it =iter(dataarray)
name = it.next()
height = it.next()
weight = it.next()
newPerson = Person(name, height,weight)
filedata.append(newPerson)
return render_template('display.html', info = page_info, fileinfo = filedata)
Any help appreciated
In this line:
with open(url_for('static', filename='bmidata.txt') as f:
you are missing one closing bracket:
with open(url_for('static', filename='bmidata.txt')) as f:
That's the reason for SyntaxError.
Opening file doesn't work this way, because open doesn't accept URL. If you need to open static file, use with app.open_resource('static/bmidata.txt') as f: or find the path of the file on the filesystem.
Related
I need to create a file that changes the date and name of a .txt, but I can only change one or the other with this code I found on the internet, can anyone give me any tips?
Print
import os
from ast import Str
file = open("example.txt", "r")
replacement = ""
data = "02/07/2022"
name = "Alan"
for line in file:
line = line.strip()
changes = line.replace("__/__/____", data)
replacement = replacement + changes + "\n"
file.close()
fout = open("final.txt", "w")
fout.write(replacement)
fout.close()
You don't need to do this a line a time. You can replace that entire program with this:
data = "02/07/2022"
name = "Alan"
text = open("example.txt", "r").read().replace("__/__/____", data)
open("final.txt", "w").write(text)
I want to search for particular text and replace the line if the text is present in that line.
In this code I replace line 125, but want to replace dynamically according to the text:
file = open("config.ini", "r")
lines = file.readlines()
lines[125] = "minimum_value_gain = 0.01" + '\n'
f.writelines(lines)
f.close()
How do I make it that if a line has:
minimum_value_gain =
then replace that line with:
minimum_value_gain = 0.01
There is no reason for you to manually parse a config.ini file textually. You should use configparser to make things much simpler. This library reads the file for you, and in a way converts it to a dict so processing the data is much easier. For your task you can do something like:
import configparser
config = configparser.ConfigParser()
config.read("config.ini")
for section in config:
if config.has_option(section, "minimum_value_gain"):
config.set(section, "minimum_value_gain", "0.01")
with open("config.ini", 'w') as f:
config.write(f)
Since you are replacing complete line so if statement will do the trick for you, no need to replace text
#updated make sure one line doesn't have both values
file = open("config.ini", "r")
lines=file.readlines()
newlines = []
for line in lines:
if "minimum_value_gain" in line:
line = "minimum_value_gain = 0.01" + '\n'
if "score_threshold" in line:
line = "Values you want to add"+'\n'
newlines.append(line)
f.writelines(newlines)
f.close()
Little bit messy and not optimized but get's the job the, first readlines and inserts the next_text to the given pos(line). If the line doesn't exists Raises IndexError, else writes to the file
def replace_in_file(filename: str, search_text: str, string_to_add: str) -> None:
with open(filename, "r+") as file_to_write:
lines = file_to_write.readlines()
file_to_write.seek(0)
file_to_write.truncate()
for line in lines:
if line.startswith(search_text):
line = line.rstrip("\n") + string_to_add + "\n"
file_to_write.write(line)
replace_in_file("sdf.txt", "minimum_value_gain", " = 0.01")
You can use also the regex library of Python.
Here is an example.
It is better not to read and write in the same file, that is not good practice. Write in a different file then eventually rename it.
import re
pattern = 'minimum_value_gain'
string_to_replace = 'minimum_value_gain = 0.01\n'
file = open("config.ini", "r")
fileout = open("new_config.ini", "a")
lines=file.readlines()
newlines = [string_to_replace if re.match(pattern, line) else line for line in lines]
f.close()
fileout.writelines(lines)
fileout.close()
You can rename the file afterwards :
import os
os.remove("config.ini")
os.rename("new_config.ini", "config.ini")
Set the string you would like to look for (match_string = 'example')
Have a list output_list that is empty
Use with open(x,y) as z: (this will automatically close the file after completion)
for each line in file.readlines() - run through each line of the file
The if statement adds your replacement line if the match_string is in the line, else just the adds the line
NOTE: All variables can be any name that is not reserved (don't call something just 'list')
match_string = 'example'
output_list = []
with open("config.ini", "r") as file:
for line in file.readlines():
if match_string in line:
output_list.append('minimum_value_gain = 0.01\n')
else:
output_list.append(line)
Maybe not ideal for the first introduction to Python (or more readable) - But I would have done the problem as follows:
with open('config.ini', 'r') as in_file:
out_file = ['minimum_value_gain = 0.01\n' if 'example' in line else line for line in in_file.readlines()]
To replace a specific text in a string
a = 'My name is Zano'
b = a.replace('Zano', 'Zimmer')
We have a text file with specific strings in it. How would we remove the strings from the file and save it as a new file?
File content before script runs:
This has foo in it.
This could also have foo in it.
There is none in here.
Competently morph 24/365 markets foo rather than inexpensive customer service.
File content after script runs:
This has in it.
This could also have in it.
There is none in here.
Competently morph 24/365 markets rather than inexpensive customer service.
Here is what we tried, but cannot figure out how to remove just the string and leave the rest of the content.
def main():
// my target string to remove
mystring = 'foo'
// open the file
f = open("myfile.txt", "r")
// second file to output content to.
f2 = open("output.txt", "w+")
// read file line by line
flines = f.readLines()
//iterate through lines
for x in flines:
// stuck here.
// how to find mystring in the line
// after removing mystring from line, append to f2
How about using re.sub():
import re
def main():
mystring = 'foo'
f = open("myfile.txt", "r")
f2 = open("output.txt", "w+")
flines = f.readLines()
result = re.sub(r"\s?{}\s?".format(mystring), " ", flines)
f2.write(result)
I have a problem with some of my python code. I want it to open a file, with few lines of text, and add header + footer to each line in that file.
The problem is that 'create_output()' function returns only the first line with additional content. If I switch 'return' to 'print' at the end of this function it properly displays all lines from my file. What could be the reason? I want to understand what am I doing wrong here.
file_path = '/home/user/Desktop/text.txt'
file_path_edited = '/home/user/Desktop/text_new.txt'
header = 'http://'
footer = '.com'
def open_file():
opened_file = open(file_path)
return opened_file
def edit_file():
edited_file = open(file_path_edited, 'w')
return edited_file
def create_output():
for line in open_file():
line = line.strip()
edited_line = header+line+footer
to_file = edit_file()
to_file.writelines(edited_line)
to_file.close()
return edited_line
print (create_output())
OK, I changed it to something like this, now it works fine.
Thanks your feedback, now I know what I'm doing wrong.
file_path = '/home/user/Desktop/text.txt'
file_path_edited = '/home/user/Desktop/text_new.txt'
header = 'http://'
footer = '.com'
def CreateContent():
with open(file_path) as read_file:
with open(file_path_edited, 'w') as write_file:
for line in read_file.readlines():
new_line = "{}{}{}".format(header, line.strip(), footer)
print(new_line)
write_file.write("{}\n".format(new_line))
CreateContent()
You get only one line, because you reopen the write-file all the time instead of letting it open, "w" will truncate the file on open - so last line lives, rest is useless IO. Also you never close your reader afaics.
open(filename, mode) from https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files:
mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.
Do not split the file open into extra functions, use with open(...) as bla: bla.write(...) so they get closed as soon as you leave the block or some exception happens.
Use string-formatting - either 'this {} ist repleaced with'.format("something") or the inline variant - see below.
def create_output():
modLines = []
with open('/home/user/Desktop/text.txt',"r") as reader, \
open('/home/user/Desktop/text_new.txt',"w") as writer:
for line in reader:
line = line.strip().rstrip('\n') # rstrip might be better if you only cut \n
modline = f'http://{line}.com' # 3.6 inline string formatting, for 2.7 use
modLines.append(modline) # 'http://{}.com'.format(line)
writer.write(modline+"\n") # write does not autoappend \n
return modlines # return a list of written https...
print (create_output())
Should do the trick.
Links:
Format string syntax
Reading and writing files
You could further improve your code as follows:
file_path = '/home/user/Desktop/text.txt'
file_path_edited = '/home/user/Desktop/text_new.txt'
header = 'http://'
footer = '.com'
def CreateContent():
with open(file_path) as read_file, open(file_path_edited, 'w') as write_file:
for line in read_file:
write_file.write("{}{}{}\n".format(header, line.strip(), footer))
CreateContent()
I have been trying for last few hours to narrow down an issue and I cannot see it. I'm new to Python 3 and trying parse a text file for a project.
The parsing simply cleans up some whitespace and replaces delimitters.
I don't understand why it won't work.
More specifically
I am getting this particular error:
"NameError: name 'out' is not defined"
Code:
save_path = 'C:/UsersDesktop/CSVproject'
with open('C:/Users/CSVproject/sourceData.dat', 'r') as f:
for line in f:
if ':DUBLIN' in line:
line = line.replace(' ', '')
line = line.replace(':', ';')
print(line)
found = True
fullNameOfFile = os.path.join(save_path, 'newFormattedData'+".csv")
out = open(fullNameOfFile, 'w')
for line in f:
out.write(line)
You are attempting to open the file each time the word :DUBLIN occurs. you only need to open it once and you should open it at a place where the scope ensures that the handle is visible to the write method.
fullNameOfFile = os.path.join(save_path, 'newFormattedData'+".csv")
out = open(fullNameOfFile, 'w')
for line in f:
if ':DUBLIN' in line:
line = line.replace(' ', '')
line = line.replace(':', ';')
print(line)
found = True
out.write(line)
And you definitely don't want to have a nested loop for iterating through the input file.