【发布时间】:2010-11-04 09:18:48
【问题描述】:
我需要在一个巨大的 Excel .csv 文件中进行查找和替换(特定于一列 URL)。由于我正处于尝试自学脚本语言的开始阶段,我想我会尝试在 python 中实现该解决方案。
我在解决方案的“替换”部分遇到问题。我已经阅读了official csv module documentation 关于如何使用编写器的内容,但对我来说并没有一个足够清晰的例子(是的,我很慢)。那么,现在的问题是:如何使用 writer 对象遍历 csv 文件的行?
附言提前为笨拙的代码道歉,我还在学习:)
import csv
csvfile = open("PALTemplateData.csv")
csvout = open("PALTemplateDataOUT.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
writer = csv.writer(csvout, dialect)
total=0;
needchange=0;
changed = 0;
temp = ''
changeList = []
for row in reader:
total=total+1
temp = row[len(row)-1]
if '/?' in temp:
needchange=needchange+1;
changeList.append(row.index)
for row in writer: #this doesn't compile, hence the question
if row.index in changeList:
changed=changed+1
temp = row[len(row)-1]
temp.replace('/?', '?')
row[len(row)-1] = temp
writer.writerow(row)
print('Total URLs:', total)
print('Total URLs to change:', needchange)
print('Total URLs changed:', changed)
【问题讨论】:
-
启动时 PALTemplateDataOUT.csv 是否为空?
-
不,它与输入文件完全相同(具有所有相同的数据)我只是不想意外覆盖我需要的任何内容
-
“意外覆盖”是什么意思?通常我们读取一个文件并写入一个不同的文件。
-
我想你是对的 - 拥有这么多副本非常愚蠢(更不用说糟糕的“做法”)。