如何通过python更改CSV文件中的值?

时间:2016-12-01 11:30:53

标签: python csv

我需要能够在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

1 个答案:

答案 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

我认为你不能直接修改文件,我想你总是要读它,修改,写入临时文件然后重命名。