在行中查找字符串以使用Python 2.7覆盖此行的CSV

时间:2015-05-07 00:56:06

标签: python csv

我正在接受另一个thread的反馈,但已经卡住了。我希望搜索现有的csv文件以找到发生字符串的行。然后我想用新数据更新这一行。

我到目前为止给了我一个" TypeError:unhasable type:' list'":

allLDR = []
with open('myfile.csv', mode='rb') as f:
    reader = csv.reader(f)
    #allLDR.extend(reader)
    for num, row in enumerate(reader):
        if myField in row[0]:
            rowNum = row

line_to_override = {rowNum:[nMaisonField, entreeField, indiceField, cadastreField]}

with open('myfile.csv', 'wb') as ofile:
    writer = csv.writer(ofile, quoting=csv.QUOTE_NONE, delimiter=',')
    #for line, row in enumerate(allLDR):
    for line, row in enumerate(reader):
        data = line_to_override.get(line, row)
        writer.writerow(data)

1 个答案:

答案 0 :(得分:1)

allDR.extend(reader)使用csv.reader对象的所有输入行。因此,for循环永远不会运行,rowNum=row永远不会执行,{rowNum:blah}会生成异常。

尝试评论allDR.extend(reader)行。

作为调试辅助工具,请尝试在for循环内和条件内添加print语句。

这是一个程序,它执行我认为您希望程序执行的操作:它读入myfile.csv,根据第一个单元格的内容有条件地修改行,然后将文件写回。

import csv

with open('myfile.csv', mode='rb') as ifile:
    allDR = list(csv.reader(ifile))

for row in allDR:
    if 'fowl' in row[0]:
        row[:] = ['duck', 'duck', 'goose']

with open('myfile.csv', 'wb') as ofile:
    csv.writer(ofile).writerows(allDR)