使用Python内置的.csv模块写入数据
[请注意,这个问题与已经回答的如何使用Python内置的.csv写入模块替换列?是不同的]
我需要在一个很大的Excel .csv文件中对某一列的URL进行查找和替换。因为我刚开始自学一种脚本语言,所以我想试着用Python来实现这个解决方案。
在我尝试修改某个条目的内容后,再写回到.csv文件时遇到了麻烦。我看过官方的csv模块文档,了解如何使用写入器,但里面没有一个例子能涵盖我的情况。具体来说,我想在一个循环中完成读取、替换和写入的操作。然而,在for循环的参数和writer.writerow()的参数中不能使用同一个'row'引用。所以,一旦我在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?)
3 个回答
问题是你在尝试从一个文件中读取内容的同时,还想往这个文件里写东西。你应该先写入到一个不同的文件里,然后再把原来的文件删掉,最后把新文件改名为原来的文件名。
以二进制模式打开csv文件是错误的。csv文件其实是普通的文本文件,所以你需要用
source = open("PALTemplateData.csv","r")
target = open("AnotherFile.csv","w")
来打开它们。
出现的错误
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
是因为你用二进制模式打开了文件。
当我用python打开excel的csv文件时,我用的是类似这样的代码:
try: # checking if file exists
f = csv.reader(open(filepath, "r", encoding="cp1250"), delimiter=";", quotechar='"')
except IOError:
f = []
for record in f:
# do something with record
这样打开的速度还挺快的(我打开了两个大约10MB的csv文件,不过那时我用的是python 2.6,而不是3.0版本)。
在python中,有几个可以处理excel csv文件的模块,其中一个是pyExcelerator。
你不能同时读取和写入同一个文件。
source = open("PALTemplateData.csv","rb")
reader = csv.reader(source , dialect)
target = open("AnotherFile.csv","wb")
writer = csv.writer(target , dialect)
处理文件的正常方法是创建一个修改过的原文件的副本。不要试图在原文件上直接更新,这样做是不明智的。
编辑
在以下代码行中:
source = open("PALTemplateData.csv","rb")
target = open("AnotherFile.csv","wb")
"rb"和"wb"是绝对必要的。每次你忽略这些,就会以错误的格式打开文件进行读取。
读取一个.CSV文件时,你必须使用"rb"。在Python 2.x中这是没有选择的。在Python 3.x中,你可以省略这个,但最好明确使用"r"来表示。
写入一个.CSV文件时,你必须使用"wb"。在Python 2.x中也是没有选择的。在Python 3.x中,你必须使用"w"。
编辑
看起来你在使用Python 3。你需要把"rb"和"wb"中的"b"去掉。
请阅读这个链接: http://docs.python.org/3.0/library/functions.html#open