有没有办法在使用 csv.dictWriter.writerow(somerow) 时防止跳过行

发布于 2024-10-12 13:31:03 字数 898 浏览 1 评论 0原文

我正在处理一些文件,并希望创建我正在处理的日志。我通过使用字典来保存每个观察的键和值来创建日志,然后将字典附加到列表(字典列表)中。

为了保存日志,我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑忘罢 2024-10-19 13:31:03

请参阅 http://docs.python.org/library/csv.html 中的文档#csv-examples

他们给出了一个 UnicodeWriter 类,如下所示:

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

See the documentation at http://docs.python.org/library/csv.html#csv-examples

They give a UnicodeWriter class as follows:

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文