Skip to main content
 首页 » 编程设计

python之如何使用 Python 的内置 .csv 编写器模块替换列

2025年05月04日16softidea

我需要在一个巨大的 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) 

请您参考如下方法:

您收到错误的原因是编写器没有要迭代的数据。你应该给它数据 - 大概你有某种列表或生成器来生成要写出的行。

我建议将两个循环组合起来,如下所示:

for row in reader: 
    row[-1] = row[-1].replace('/?', '?') 
    writer.writerow(row) 

这样,您甚至不需要total、needchange 和changeList。 (那里有一堆优化,很遗憾我没有时间解释,但我会看看我是否可以稍后编辑这些信息)