0

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.

2
  • Read the file and turn it into a easy to use data structure. Then, you can modify it and write it back. Commented Jun 6, 2013 at 18:54
  • 2
    Define "number". Which of the following are numbers? 1, two, 4e18, 3.14159, 0x5f3759df Commented Jun 6, 2013 at 19:00

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

21 Comments

And you should make sure the individual entries do not contain the delimiter string without taking precautions. In this case, (e.g.) ingredient names should not contain tab characters.
It seemed very hopeful, and a good solution, but it returns 'IndexError: list index out of range' for the 'line[2] = float(line[2]) * serve'
@JohnSmith some of your lines must not have all the necessary entries. Perhaps it's because each line begins with a newline (\n), meaning the first line only has one entry. I'll modify the code accordingly; let me know if it works.
thanks for the quick response!! But I get a TypeError... it says 'TypeError: can't multiply sequence by non-int of type 'float''. Is this a problem because a different part of my code?
@JohnSmith What does serve contain? Is it a float, an integer, or something else? If it's not a number then that might be causing the problem.
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.