[英]Python- how to write to text file without deleting contents
我是编程新手,想知道是否有人可以帮助我。 我在下面创建了一个程序,使我能够写入文本文件。 我有第三列,名为flower_quantity。 我想知道如何在不覆盖flower_quantity 的情况下使用下面的代码更新文本文件。
def feature_4(flower_file='flowers.txt'):
flower_update = input("Enter the name of the flower you wish to change the price:"
"Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
flower_new_price = input("Enter the updated price of the flower")
flower, price = [], []
with open(flower_file) as amend_price:
for line in amend_price:
spt = line.strip().split(",")
flower_price = int(spt[1])
flower_name = str(spt[0])
if flower_name == flower_update :
price.append(flower_new_price)
else:
price.append(flower_price)
flower.append(flower_name)
with open(flower_file, "w") as f_:
for i, v in enumerate(flower):
f_.write("{},{}\n".format(v, str(price[i])))
print("The new price of", flower_update, "is", flower_new_price)
with open(path, 'a')
将以 append 模式打开您的文件,该模式不会删除内容并将插入符号放在文件末尾,因此所有内容都将添加到文件末尾。
您可以找到所有可用文件打开模式的许多评论,例如https://stackabuse.com/file-handling-in-python/
以append模式打开文件
with open(flower_file,"a+"):
如果文件不存在, +
号会创建一个新文件
这将从文件的最后写入点开始 append 文件。 从新行到 append,你应该从 \n 开始
有几种方法可以完成这项工作。
但是按照您已经这样做的方式,您可以在读取文件时仅包含数量。 代码看起来有点像这样。
def feature_4(flower_file='flowers.txt'):
flower_update = input("Enter the name of the flower you wish to change the price:"
"Lily, Rose, Tulip, Iris, Daisy, Orchid, Dahlia, Peony")
flower_new_price = input("Enter the updated price of the flower")
flower, price, quantity = [], [], []
with open(flower_file) as amend_price:
for line in amend_price:
spt = line.strip().split(",")
flower_price = int(spt[1])
flower_name = str(spt[0])
quantity.append(str(spt[2]))
if flower_name == flower_update :
price.append(flower_new_price)
else:
price.append(flower_price)
flower.append(flower_name)
with open(flower_file, "w") as f_:
for i, v in enumerate(flower):
f_.write("{},{},{}\n".format(v, str(price[i]),quantity[i]))
print("The new price of", flower_update, "is", flower_new_price)
或者,如果您确实想要更新而不是覆盖整个文件,则需要使用open('txtfile.txt','a+')
打开文件。 并导航到您想要 append 的指定行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.