Store networkx graph object

Question:

I have a huge graph with about 5000 nodes that I made it with networkX. It takes about 30 seconds to create this graph each time I execute my script. After this relatively long time I can run my analysis like shortest_path and so on.

My question is, is there any way to store the object of this graph in file or something like this and each time I run my script, networkX read that file and load all of my graph?

Asked By: Ali-T

||

Answers:

You could use gpickle to do this. Assuming your graph is denoted with G, you could save it by:

nx.write_gpickle(G,'myGraph.gpickle')

and load it with

G = nx.read_gpickle('myGraph.gpickle')

https://networkx.org/documentation/stable//reference/readwrite/gpickle.html#pickled-graphs

Answered By: seulberg1

As of version 2.6, methods write_gpickle and read_gpickle are deprecated. Try this instead:

import pickle

# save graph object to file
pickle.dump(G, open('filename.pickle', 'wb'))

# load graph object from file
G = pickle.load(open('filename.pickle', 'rb'))

Note the options 'wb' to dump and 'rb' to load in open().

Answered By: PatrickT
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.