Python 将Ascii 7位解码为可读的UTF8.CSV文件
我希望有人能帮我处理部分代码,输出文件中有一个问题,该文件应该是使用unicode的.csv格式,在excel上易于阅读。问题是输出文件没有格式,其中的文本是ASCII(7bit) 我真的很感谢你的帮助,我已经做了4个小时了,还没有发现问题:/ 脚本的最后一部分:Python 将Ascii 7位解码为可读的UTF8.CSV文件,python,windows,csv,utf-8,decode,Python,Windows,Csv,Utf 8,Decode,我希望有人能帮我处理部分代码,输出文件中有一个问题,该文件应该是使用unicode的.csv格式,在excel上易于阅读。问题是输出文件没有格式,其中的文本是ASCII(7bit) 我真的很感谢你的帮助,我已经做了4个小时了,还没有发现问题:/ 脚本的最后一部分: class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the give
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)
Python版本在Windows10上是2.7
是Ascii格式,使用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)
这是哪一个版本的python?你忘了写BOM了吗?你写的数据都是ascii码吗?如果没有非ascii字符,ascii和utf-8看起来是相同的。在windows 10上,Python版本是2.7,代码在Asciia中。您是否坚持使用2.7,或者是否可以更新到3.x,后者对unicode有更强大的支持?3.x已经推出很多年了,如果你遇到问题,3.x是专门为解决这个问题而设计的。。。然后往前走。