有没有办法在使用 csv.dictWriter.writerow(somerow) 时防止跳过行
我正在处理一些文件,并希望创建我正在处理的日志。我通过使用字典来保存每个观察的键和值来创建日志,然后将字典附加到列表(字典列表)中。
为了保存日志,我使用 Python 的 csv 模块来写出字典列表。最初我使用 writerows 但遇到一个问题,因为我存储的某些值很少是 ascii 以外的值,
例如
Investee\xe2\x80\x99s Share of Profits
我的解决方案是使用 try / except 语句迭代我的字典列表以跳过问题字典
for docnumb, item in enumerate(x[1]):
try:
dict_writer.writerow(item)
except UnicodeEncodeError:
missed.append(docnumb)
item
但是,这会导致在输出 csv 文件的每一行中插入额外的行。
value1 value2 value3 etc . . .
#blank row
value1 value2 value3 etc
我不知道如何抑制这种行为。
多一点代码,这样我就可以更清楚地了解我是如何到达这里的
import csv
keyset=set([])
for item in x[1]:
keyset |=set(item.keys())
keys=list(keyset)
logref=open(r'c:\December_2010_File_list.csv','w')
dict_writer=csv.DictWriter(logref,keys)
keyset |=set(item.keys())
I am processing some files and want to create a log of what I am processing. I created the log by using a dictionary to hold the keys and values for each observation and then I am appending the dictionary to a list (a list of dictionaries).
To save the log I am using Python's csv module to write out the list of dictionaries. Initially I was using writerows but I encountered a problem in that very infrequently some of the values I am storing are something other than ascii
example
Investee\xe2\x80\x99s Share of Profits
my solution was to iterate through my list of dictionaries using try / except statements to skip over the problem dictionaries
for docnumb, item in enumerate(x[1]):
try:
dict_writer.writerow(item)
except UnicodeEncodeError:
missed.append(docnumb)
item
However, this leads to an extra row being inserted in each line of the output csv file.
value1 value2 value3 etc . . .
#blank row
value1 value2 value3 etc
I can't see how to suppress this behavior.
a little more code so there is more clarity about how I got here
import csv
keyset=set([])
for item in x[1]:
keyset |=set(item.keys())
keys=list(keyset)
logref=open(r'c:\December_2010_File_list.csv','w')
dict_writer=csv.DictWriter(logref,keys)
keyset |=set(item.keys())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 http://docs.python.org/library/csv.html 中的文档#csv-examples
他们给出了一个 UnicodeWriter 类,如下所示:
See the documentation at http://docs.python.org/library/csv.html#csv-examples
They give a UnicodeWriter class as follows: