我想在一个CSV文件编辑一行。我有一个CSV文件看起来像波纹管:
TYPE |食品种类|供应时间|洗涤时间
LION |肉类| 4H | 1D
FOX |肉类| 5H | 3D
HEN |种子| 6H | 6D
FISH |植物| 7H | 99D
我想编辑基于其类型的行。如果用户希望编辑FOX行他们只需要在提示时输入FOX。我现在面临的问题是,我不能编辑出于某种原因该文件。
我的代码波纹管,我打开现有的数据库,发现有问题的行,改变它,然后写出来,与其他行一起,成为我可以覆盖原来的临时文件。
def edit_animal_entry(type):
with open(animal_csv, 'r') as file_read:
reader = csv.reader(file_read, delimiter="|")
with open(temp, 'w') as file_write:
writer = csv.writer(file_write)
for row in reader:
print(f"{' | '.join(row)}")
if row[0] == type:
animal_type, animal_food, animal_feed, animal_wash = animal_inputs()
writer.writerow([animal_type, animal_food, (animal_feed+"H"), (animal_wash+"D")])
else:
writer.writerow(row)
shutil.move(temp, animal_csv)
您已经阅读任何东西出来之前停止with
块“封闭”的读取文件。所以你是不是循环您的输入文件。一个解决办法是打开输入,并在同一输出文件用语句:
def edit_animal_entry(type):
with open(animal_csv, 'r') as file_read, open(temp, 'w') as file_write:
reader = csv.reader(file_read, delimiter="|")
writer = csv.writer(file_write)
for row in reader:
print(f"{' | '.join(row)}")
if row[0] == type:
animal_type, animal_food, animal_feed, animal_wash = animal_inputs()
writer.writerow([animal_type, animal_food, (animal_feed+"H"), (animal_wash+"D")])
else:
writer.writerow(row)
shutil.move(temp, animal_csv)