Problem uploading a graph from a pickle file

Viewed 436

As a part of a program, I have to read a graph from a pickle file and then return it as a graph. I must say I'm using OSMnx and networkx to do so.

I already have this pickle file containing a graph downloaded from OSMnx. But as I call the function it raises an error.

Code:

import networkx
import osmnx as ox
import requests
import matplotlib.cm as cm
import matplotlib.colors as colors
import pickle
ox.config(use_cache=True, log_console=True)
ox.__version__


def load_graph(filename):
    """Uploads a graph from a pickle file and it returns it"""
    infile = open(filename, 'rb')
    G = pickle.load(infile)
    infile.close()
    return G


def main():
    ox.plot_graph(load_graph("graph1.pickle"))

main()

Error:

AttributeError: 'str' object has no attribute 'nodes'

What should I do?

1 Answers

You didn't provide a reproducible code snippet (e.g., I don't know how you generated the graph1.pickle file or what it contains), but this similar code snippet works fine with pickling:

import osmnx as ox
import pickle
ox.config(use_cache=True, log_console=True)
G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive')
pickle.dump(G, open('graph.pickle', 'wb'))
G2 = pickle.load(open('graph.pickle', 'rb'))
fig, ax = ox.plot_graph(G2)

As an aside: as an alternative to pickling for graph serialization, you can also use OSMnx's built-in save_graphml and load_graphml functions.

Related