'Python-AttributeError: 'int' object has no attribute 'decode'" when trying to call the GML file on NetworkX

Premise・What I want to achieve

I'm going to use Python to read the GML file.

Error Message

Traceback (most recent call last):
  File "firstgml.py", line 9, in <module>
    G = nx.read_gml(gml_path)
  File "<decorator-gen-434>", line 2, in read_gml
  File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/utils/decorators.py", line 227, in _open_file
    result = func_to_be_decorated(*new_args, **kwargs)
  File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 218, in read_gml
    G = parse_gml_lines(filter_lines(path), label, destringizer)
  File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 398, in parse_gml_lines
    graph = parse_graph()
  File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 387, in parse_graph
    curr_token, dct = parse_kv(next(tokens))
  File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 315, in tokenize
    for line in lines:
  File "/Users/XXXX/.pyenv/versions/3.8.5/lib/python3.8/site-packages/networkx/readwrite/gml.py", line 209, in filter_lines
    line = line.decode('ascii')
AttributeError: 'int' object has no attribute 'decode'

Corresponding source code

import numpy as np
import networkx as nx

gml_path = "XXXX.gml"
gml_path = gml_path.encode("utf-8")
G = nx.read_gml(gml_path)
X = np.array(nx.to_numpy_matrix(G))
print(nx.is_directed(G))

What I tried

I changed the encoding character code to ascii and so on, but I get an error.

Supplementary information (FW / tool version, etc.)

Python 3.85

networkx 2.1

numpy 1.19.2



Solution 1:[1]

This is the part that is wrong.

gml_path = "XXXX.gml"
gml_path = gml_path.encode("utf-8")
G = nx.read_gml(gml_path)

You shouldn't be encoding the name of the file. read_gml takes a filename or a filehandle. When you pass the encoded gml_path it thinks it is an open file, so it goes to iterate over it. And when it goes to do line.decode('ascii'), the line variable contains b'X' which transfers to the number 88.

gml_path = "XXXX.gml"
gml_path = gml_path.encode("utf-8")
print(gml_path[0])
>>> 88

The error you were getting before: "NetworkXError: input is not ASCII-encoded" is because your file is not properly encoded, not your path to file. What you should do is remove this line gml_path = gml_path.encode("utf-8"), and encode your GML file, either with another tool, or using Python.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marko