【发布时间】:2016-06-27 13:03:27
【问题描述】:
我正在尝试从 csv 文件中读取数据,然后根据用户选择更新字段并将内容(包括修改)写入新的 csv 文件。我已经管理了一切,但我的解决方案只写了修改后的行,而不是其余的文件内容。
csv 文件如下所示:
1001, item1, 0.5, 10
1002, item2, 1.5, 20
这是我尝试的一个例子:
run="yes"
while run=="yes":
id=input("Enter the id of the product you want to order: ")
amount=input("Enter the quantity: ")
reader = csv.reader(open('items.csv', 'r'))
writer = csv.writer(open('updatedstock.csv','w'))
for row in reader:
if id==row[0]:
name=row[1]
price=row[2]
stock=row[3]
newstock=int(stock)-int(amount)
writer.writerow([id, name, price, newstock])
run=input("Do you want to order another item? yes/no ")
【问题讨论】:
标签: python-3.x csv