[请注意,这与已经回答的如何使用 Python 的内置 .csv 编写器模块替换列?]
我需要在一个巨大的 Excel .csv 文件中进行查找和替换(特定于一列 URL)。由于我正处于尝试自学脚本语言的开始阶段,我想我会尝试在 python 中实现该解决方案。
在更改条目的内容后尝试写回 .csv 文件时遇到问题。我已阅读有关如何使用编写器的官方 csv 模块文档,但没有涵盖这种情况的示例。具体来说,我试图在一个循环中完成读取、替换和写入操作。但是,不能在 for 循环的参数和 writer.writerow() 的参数中使用相同的“行”引用。那么,一旦我在 for 循环中进行了更改,我应该如何写回文件?
编辑:我实施了 S. Lott 和 Jimmy 的建议,结果仍然相同
编辑#2:根据 S. Lott 的建议,我在 open() 函数中添加了“rb”和“wb”
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)
编辑:供您参考,这是来自解释器的新的完整回溯:
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?)