Note
Go to the end to download the full example code.
Read and write graphs.#
Read and write graphs.
import io
import matplotlib.pyplot as plt
import networkx as nx
G = nx.grid_2d_graph(5, 5) # 5x5 grid
# Use BytesIO as a virtual file handle.
# Replace with: `with open(<filename>, "wb") as fh:` to save to disk
fh = io.BytesIO()
# write edgelist to file
nx.write_edgelist(G, path=fh, delimiter=":")
# View file contents
print(fh.getvalue().decode())
# read edgelist from file
fh.seek(0)
(0, 0):(1, 0):{}
(0, 0):(0, 1):{}
(0, 1):(1, 1):{}
(0, 1):(0, 2):{}
(0, 2):(1, 2):{}
(0, 2):(0, 3):{}
(0, 3):(1, 3):{}
(0, 3):(0, 4):{}
(0, 4):(1, 4):{}
(1, 0):(2, 0):{}
(1, 0):(1, 1):{}
(1, 1):(2, 1):{}
(1, 1):(1, 2):{}
(1, 2):(2, 2):{}
(1, 2):(1, 3):{}
(1, 3):(2, 3):{}
(1, 3):(1, 4):{}
(1, 4):(2, 4):{}
(2, 0):(3, 0):{}
(2, 0):(2, 1):{}
(2, 1):(3, 1):{}
(2, 1):(2, 2):{}
(2, 2):(3, 2):{}
(2, 2):(2, 3):{}
(2, 3):(3, 3):{}
(2, 3):(2, 4):{}
(2, 4):(3, 4):{}
(3, 0):(4, 0):{}
(3, 0):(3, 1):{}
(3, 1):(4, 1):{}
(3, 1):(3, 2):{}
(3, 2):(4, 2):{}
(3, 2):(3, 3):{}
(3, 3):(4, 3):{}
(3, 3):(3, 4):{}
(3, 4):(4, 4):{}
(4, 0):(4, 1):{}
(4, 1):(4, 2):{}
(4, 2):(4, 3):{}
(4, 3):(4, 4):{}
0
Note that the original graph G had tuples as nodes. In order to recover
the original node type, the data read from file must be properly interpreted
using the nodetype kwarg

Total running time of the script: (0 minutes 0.023 seconds)