我是python新手,在尝试运行下面的代码时,一直出现上面的错误。有谁能帮忙或提供指导吗,谢谢:)
def feature_4():
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")
with open('flowers.txt') as amend_price:
for line in amend_price:
flower_price = int(line.split(',')[1])
flower_name = str(line.split(',')[0])
if flower_name == flower_update:
flower_price.append(flower_new_price)
print("The new price of", flower_update, "is", flower_new_price)
解决方案:
你碰到了一个常见的问题,你不能同时读取一个文件和修改它.至少我不知道如何做到这一点,你可以使用几个选项来实现你的目标。
当用 “w “标志写的时候,你会擦掉现有的文件,因此你要先读取内存中的文件,修改它,把它的数据保留在内存或临时文件中,然后重写它。
我将跳过临时文件。
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")
# here you should check that the input matches what you are expecting
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)