我是编程新手,不知道有没有人能帮我。我已经在下面创建了一个程序,使我能够写入文本文件。我还有第三个专栏,叫做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)发布于 2020-04-26 19:28:51
with open(path, 'a')会在附加模式下打开你的文件,它不会删除文件的内容,也不会把插入符号放在文件的末尾,所以所有的内容都会添加到文件的末尾。
您可以找到许多关于所有可用的文件打开模式的评论,例如https://stackabuse.com/file-handling-in-python/
发布于 2020-04-26 19:34:24
在追加模式下打开文件
with open(flower_file,"a+"):
如果文件尚不存在,则+符号会创建一个新文件
这将从上次写入的点追加文件。要从新行追加,应以\n
发布于 2020-04-26 20:15:59
有几种方法可以完成这个任务。
但是按照您已经这样做的方法,您可以在读取文件时只包含数量。代码看起来有点像这样。
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+')打开该文件。并导航到要追加的指定行。
https://stackoverflow.com/questions/61439897
复制相似问题