【发布时间】: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