如何通过python更改CSV文件中的值? [英] How do you change a value in a CSV file through python?
问题描述
我需要能够找到和更改CSV股票文件中的值.我知道如何搜索值,但是当我尝试使用csv.writer
时,它将返回错误.
I need to be able to find and change a value in a CSV stock file. I know how to search for a value but when I try to use the csv.writer
then it returns an error.
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
我不知道为什么要这么做.到目前为止,我的代码是这样的:
I have no idea why it is doing that. So far I have this for the code:
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
Can anyone tell me how to fix the error or if there is another way to modify the value. I am using python 3.2.3
推荐答案
尝试一下:
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
,则不必关闭文件.
If you use with open
instead of open
you don't have to close the file.
代码的工作方式如下:
- 读取库存水平(您可能必须将定界符更改为任何 你有)
- 查看库存水平的每一行,如果看到,请对其进行修改 您要搜索的代码
- 将所有级别的库存水平写回到新库存 级别,包括修改后的行
- 删除旧文件以将
New Stock Levels.csv
文件重命名为旧版本(确保已备份) - 将
New Stock Levels.csv
重命名为Stock Levels.csv
- Read stock levels (you might have to change the delimiter to whatever you have)
- Look at each line in stock levels and modify it if you see your code to search
- Write ALL lines of stock levels back to new stock levels, including the modified lines
- Delete the old file to enable the
New Stock Levels.csv
file to be renamed to the older version (make sure you have a backup) - Rename
New Stock Levels.csv
toStock Levels.csv
我认为您不能直接修改文件,我认为您始终必须先读取,修改,写入临时文件,然后重命名.
I don't think you can modify a file directly, I think you always have to read it, modify, write to temp file and then rename.
这篇关于如何通过python更改CSV文件中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!