UnicodeDecodeError for writing file

﹥>﹥吖頭↗ 提交于 2019-12-02 02:58:13

问题


I know that this is a very common error, but it's the first time I've encountered it when trying to write a file.

I'm using networkx to work with graphs for network analysis, and when I try to write into any format:

nx.write_gml(G, "Graph.gml")
nx.write_pajek(G, "Graph.net")
nx.write_gexf(G, "graph.gexf")

I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in write_pajek
  File "/Library/Python/2.7/site-packages/networkx/utils/decorators.py", line 263, in _open_file
    result = func(*new_args, **kwargs)
  File "/Library/Python/2.7/site-packages/networkx/readwrite/pajek.py", line 100, in write_pajek
    path.write(line.encode(encoding))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)

I haven't found documentation on this, so quite confused.


回答1:


Wondering if you can make use of codec module to solve it or not. Just create a file object by codec as following before feeding to networkx.

ex,

import codecs
f = codecs.open("graph.gml", "w", "utf-8")


来源:https://stackoverflow.com/questions/16097217/unicodedecodeerror-for-writing-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!