在Python中从XML写入CSV,编码错误
我正在尝试将 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 字符。有什么建议吗?
I am trying to convert an XML file to CSV, but the encoding of the XML ("ISO-8859-1") apparently contains characters that are not in the ascii codec which Python uses to write rows.
I get the error:
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)
I have tried opening the file as follows:
dom1 = parse(input_filename.encode( "utf-8" ) )
and I have tried replacing the \xe1 character in each row before it is written. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
xml 解析器返回
unicode
对象。这是一件好事。问题是,csv
模块无法处理它们。您可以在将 xml 解析器返回的每个
unicode
字符串交给csv
编写器之前进行编码,但更好的主意是使用此 csvUnicodeWriter
Recipe 来自csv
模块的官方文档:The xml parser returns
unicode
objects. That's a good thing. Thing is,csv
module can't deal with them.You could encode each
unicode
string returned by the xml parser before handing to thecsv
writer, but a better idea is to use this csvUnicodeWriter
recipe from the official docs of thecsv
module: