python 3 - 查找并替换文本文件中的所有数字

时间:2013-06-06 18:51:55

标签: python string integer

我意识到在文本文件中查找和替换已经被问到了,但我不确定如何将它应用到我的情况中。

基本上,这在程序的早期进行:

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)

稍后,我需要阅读文本文件。但是,我需要将数字(quant)替换为用户输入的不同数字的数字。目前我有这个,但我知道这一切都错了。

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")

line.replace部分目前是伪造的,因为我不知道该放什么... 对不起,如果这是一个noobie问题,但我真的坚持这个。 谢谢你的聆听!

2 个答案:

答案 0 :(得分:2)

当您编写文件时,请帮自己一个忙,并在不同的条目之间添加某种分隔符:

f.write("\t".join(["\ningredient: ", ingredient, quant, unit]))

然后当您再次打开文件时,您可以使用该分隔符拆分每一行的字符串,并对第三个条目(quant中的数字所在的位置)进行操作:

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。有更好的方法来存储python数据(例如picklesCSV),但这应该适用于您当前的实现而不需要太多修改。

答案 1 :(得分:0)

您可以尝试这样的事情:

    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)

看看这个:Search and replace a line in a file in Python