将Ascii 7位解码为可读的UTF8 .CSV文件

时间:2017-04-10 16:41:46

标签: python windows csv utf-8 decode

我希望有人帮我处理部分代码,输出文件中存在问题,应该使用unicode以.csv格式显示,易于在excel上阅读。问题是输出文件没有格式,其中的文本是ASCII(7位)。

我真的很感谢你的帮助我现在已经有4个小时没有找到这个问题但仍然无法找到问题:/

脚本的最后一部分:

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").replace("\n"," ").replace("\r"," ").replace("\t",'') 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)

Windows 10上的Python版本是2.7 是在Ascii

1 个答案:

答案 0 :(得分:0)

使用unicode编写.csv格式,例如:

import io, csv

outfile = 'test/out.csv'
fieldnames = ['field1', 'field2']
content_dict = {'field1':'John', 'field2':'Doo'}

with io.open(outfile, 'w', newline='', encoding='utf-8') as csv_out:
    writer = csv.DictWriter(csv_out, fieldnames=fieldnames)
    writer.writeheader()

    for row_dict in content_dict:
        writer.writerow(row_dict)