我需要能够在CSV库存文件中查找和更改值。我知道如何搜索值,但当我尝试使用csv.writer
时,它会返回错误。
Traceback (most recent call last):
File "\\pbsrvfile\ExamAccounts$\ITCA76\ochot_krystian_a453\Task 3\Task 3.pyw", line 8, in <module>
for row in writer:
TypeError: '_csv.writer' object is not iterable
我不知道为什么这样做。到目前为止,我有这个代码:
import csv
code=input('Enter code to search: ')
stock=open ('Stock Levels.csv', 'wb')
writer=csv.writer(stock)
for row in writer:
for field in row:
if field==code:
print('Record found! \n')
print('Code: '+row[0])
print('Product name: '+row[1])
print('Target level: '+row[2])
target = int(row[2])
print('Current level: '+row[3]+'\n')
current = int(row[3])
restock_amount = target - current
restocked_value = restock_amount + current
writer.writerow[3](restocked_value)
print(row[1]+' has been restocked to '+restocked_value)
任何人都可以告诉我如何修复错误或者是否有其他方法来修改该值。我使用的是python 3.2.3
答案 0 :(得分:2)
试试这个:
import csv
import os
code=input('Enter code to search: ')
with open ('Stock Levels.csv', 'r') as stock:
reader=csv.reader(stock, delimiter=',')
with open ('New Stock Levels.csv', 'w') as newStock:
writer=csv.writer(newStock, delimiter=',')
for row in reader:
if code in row:
print('Record found! \n')
print('Code: '+row[0])
print('Product name: '+row[1])
print('Target level: '+row[2])
target = int(row[2])
print('Current level: '+row[3]+'\n')
current = int(row[3])
restock_amount = target - current
restocked_value = restock_amount + current
row[3] = restocked_value
print(row[1]+' has been restocked to '+str(restocked_value))
writer.writerow(row)
os.remove('Stock Levels.csv')
os.rename('New Stock Levels.csv', 'Stock Levels.csv')
如果您使用with open
代替open
,则无需关闭该文件。
代码的工作原理如下:
New Stock Levels.csv
文件重命名为旧版本(确保备份)New Stock Levels.csv
重命名为Stock Levels.csv
我认为你不能直接修改文件,我想你总是要读它,修改,写入临时文件然后重命名。