[请注意,这是一个与已经回答的问题不同的问题如何使用 Python 的内置 .csv writer 模块替换列? https://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module]
我需要在一个巨大的 Excel .csv 文件中进行查找和替换(特定于一列 URL)。由于我正处于尝试自学脚本语言的开始阶段,我想我会尝试在 python 中实现该解决方案。
当我在更改条目内容后尝试写回 .csv 文件时遇到问题。我读过官方 csv 模块文档 http://docs.python.org/3.0/library/csv.html关于如何使用 writer,但没有涵盖这种情况的示例。具体来说,我试图在一个循环中完成读取、替换和写入操作。但是,不能在 for 循环的参数和 writer.writerow() 的参数中使用相同的“行”引用。那么,一旦我在 for 循环中进行了更改,我应该如何写回文件?
edit:我执行了S. Lott和Jimmy的建议,结果还是一样
edit #2:根据 S. Lott 的建议,我将“rb”和“wb”添加到 open() 函数中
import csv
#filename = 'C:/Documents and Settings/username/My Documents/PALTemplateData.xls'
csvfile = open("PALTemplateData.csv","rb")
csvout = open("PALTemplateDataOUT.csv","wb")
reader = csv.reader(csvfile)
writer = csv.writer(csvout)
changed = 0;
for row in reader:
row[-1] = row[-1].replace('/?', '?')
writer.writerow(row) #this is the line that's causing issues
changed=changed+1
print('Total URLs changed:', changed)
edit:供您参考,这是new来自解释器的完整回溯:
Traceback (most recent call last):
File "C:\Documents and Settings\g41092\My Documents\palScript.py", line 13, in <module>
for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)