Reputation: 1
I realise that finding and replacing in a text file has already been asked, but I wasn't sure how to apply it to my situation.
Basically, this goes on earlier in the program:
while True:
ingredient = input("what is the name of the ingredient? ")
if ingredient == "finished":
break
quant = input("what is the quantity of the ingredient? "))
unit = input("what is the unit for the quantity? ")
f = open(name+".txt", "a")
f.write("\ningredient: "+ingredient+quant+unit)
Later on, I need to read the text file. However, I need to replace the numbers (quant) with the number times a different number that's inputted by the user. At the moment I have this, but I know it's all wrong.
file2 = open(recipe+".txt", "r")
file3 = open(recipe+".txt.tmp", "w")
for line in file2:
file3.write(line.replace(numbers,numbers * serve))
print(file3)
os.remove(recipe+".txt.tmp")
the line.replace part is currently psuedocode as I'm not sure what to put there... Sorry if it's a noobie question, but I'm really stuck on this. Thanks for listening!
me.
Upvotes: 0
Views: 2379
Reputation: 11381
When you're writing the file, do yourself a favor and put some kind of delimiter between the different entries:
f.write("\t".join(["\ningredient: ", ingredient, quant, unit]))
Then when you open the file again, you can just split the string of each line using that delimiter and operate on the third entry (which is where the number from quant
will be):
lines = file2.readlines()
for line in lines[1:]: # To skip the first empty line in the file
line = line.split("\t")
line[2] = str(float(line[2]) * int(serve))
file3.write("\t".join(line))
N.B. There are better ways to store python data (like pickles or CSV), but this should work with your current implementation without much modififcation.
Upvotes: 2
Reputation: 1
You could try something like this :
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
old_file = open(file_path)
for line in old_file:
new_file.write(line.replace(pattern, subst))
#close temp file
new_file.close()
close(fh)
old_file.close()
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
Check out this : Search and replace a line in a file in Python
Upvotes: 0