[英]In python writing from XML to CSV, encoding error
我正在尝试将XML文件转换为CSV,但是XML的编码(“ ISO-8859-1”)显然包含了Python用来写行的ascii编解码器中没有的字符。
我收到错误:
Traceback (most recent call last):
File "convert_folder_to_csv_PLAYER.py", line 139, in <module>
xml2csv_PLAYER(filename)
File "convert_folder_to_csv_PLAYER.py", line 121, in xml2csv_PLAYER
fout.writerow(row)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128)
我尝试如下打开文件: dom1 = parse(input_filename.encode( "utf-8" ) )
并且我尝试在写入之前替换每行中的\\ xe1字符。 有什么建议么?
xml解析器返回unicode
对象。 这是好事。 问题是, csv
模块无法处理它们。
你可以编码每个unicode
移交给前XML解析器返回的字符串csv
作家,而是一个更好的主意是使用这个CSV UnicodeWriter
配方从官方文档csv
模块:
import csv, codecs, cStringIO
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.