【问题标题】:decoding Ascii 7 bits to a readable UTF8 .CSV file将 Ascii 7 位解码为可读的 UTF8 .CSV 文件
【发布时间】:2017-04-10 16:41:45
【问题描述】:

我希望有人帮助我处理我的部分代码,输出文件存在问题,应该使用 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 中

【问题讨论】:

  • 这是哪个版本的python?
  • 您忘记写BOM了吗?
  • 你写的数据都是ascii的吗?如果没有非 ascii 字符,ascii 和 utf-8 看起来相同。
  • Windows 10 上的 Python 版本为 2.7,代码在 Ascii 中
  • 您是坚持使用 2.7 还是可以更新到对 unicode 有更强大支持的 3.x? 3.x 已经推出很多年了,如果您遇到问题 3.x 是专门为解决问题而设计的......然后继续前进。

标签: python windows csv utf-8 decode


【解决方案1】:

使用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)

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2012-03-18
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多