Python的CSV:写入文件
问题描述:
我写的是,根据用户供应CSV的行数行为的简单功能时保持头,通过添加或删除列:Python的CSV:写入文件
def sanExt(ifpath, ofpath):
with open(ifpath, "rb") as fin, open(ofpath, "wb") as fout:
csvin = csv.reader(fin)
csvout = csv.writer(fout, delimiter=",")
fline = csvin.next()
if len(fline) == 33:
for row in csvin:
row.insert(10, "NULL")
csvout.writerow(row)
print "AG"
elif len(fline) == 35:
print "AI"
elif len(fline) == 36:
print "AJ"
else:
print "Unknown"
我已经在第一个if
声明停止,只是为了确保我的代码工作。在这种情况下,该列已正确添加,但标题已丢失。
如何确保每一行都写入文件,而不仅仅是[1:len(rows)]
?
我的方法是完成预期工作的合适pythonic方式吗?
答
如果您不需要csv.DictReader
用于通过列名访问,那么传统的解决方案是根据各地类似以下内容:
with open('in.csv') as fin, open('out.csv', 'wb') as fout:
csvin = csv.reader(fin)
csvout = csv.writer(fout)
try:
header = next(csvin)
csvout.writerow(header)
except StopIeration as e:
pass # empty file - either handle, or we'll just continue and drop out of loop
for row in csvin:
csvout.writerow(row) # do some real work here...
+0
刚刚删除我的答案,这正是你的建议。我通过试验和错误,而不是代码福。谢谢。 – CHM 2012-07-24 10:58:09
在报告异常(类型错误),回溯总是有益的。否则,告诉我们什么路线提出异常比你给我们的更好。 – msw 2012-07-24 10:32:47
Quotes the docs:“请注意,与DictReader类不同,DictWriter的fieldnames参数不是可选的,因为Python的dict对象没有排序,所以没有足够的信息来推断该行应该写入csvfile“。并查看http://docs.python.org/library/csv.html#csv.csvreader.fieldnames – msw 2012-07-24 10:38:48