lorenzog
lorenzog

Reputation: 3609

Loading and saving graphs in python

I need to create a graph based on a set of input files. Since those files could be loaded during separate iterations, I need to save the graph and be able to add to it after re-loading the graph information from file.

The obvious choice seems graphviz but the python API doesn't seem to allow loading. PyDot has a parse_dot_data file and is also referenced in this answer but the documentation is non-existing and there's no clear way to 'append' to a graph. Then there's networkX which seem to have the ability to load although it's nowhere in the documentation to be found. Lastly there's graph-tool which is overkill and requires more libraries and tool than I need for this simple job.

I'm sure this must be a solved problem and I'm reluctant to "reinvent the wheel" and write a database/persistence layer to accomplish this.

How can I make a simple graph in Python, save it somewhere and load it when needed?

Upvotes: 2

Views: 857

Answers (1)

SparkAndShine
SparkAndShine

Reputation: 18017

NetworkX provides abundant file formats for reading and writing graphs. Refer to Reading and writing graphs for the detailed description. For instance,

import networkx as nx

# Create a graph
G = nx.florentine_families_graph()

# Save to a file
filename = 'florentine_families_graph.graphml'
G = nx.write_graphml(G, filename)

# Load from a file
filename = 'florentine_families_graph.graphml'
G = nx.read_graphml(filename)

Upvotes: 2

Related Questions