Python package for creating and manipulating graphs and networks
—
Reading and writing graphs in various file formats including adjacency lists, edge lists, GraphML, GML, GEXF, Pajek, and other standard formats. NetworkX provides comprehensive I/O support for interoperability with other graph analysis tools.
Simple text format with one edge per line, optionally with edge attributes.
def read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8'):
"""
Read graph from edge list file.
Parameters:
- path: File path or file handle
- comments: Character marking comment lines
- delimiter: String used to separate values
- create_using: Graph constructor
- nodetype: Convert node identifiers to this type
- data: If True, load edge attributes
- edgetype: Convert edge data to this type
- encoding: Text encoding
Returns:
NetworkX graph
"""
def write_edgelist(G, path, comments='#', delimiter=' ', data=True, encoding='utf-8'):
"""Write graph to edge list file."""
def read_weighted_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, encoding='utf-8'):
"""Read graph from weighted edge list file."""
def write_weighted_edgelist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
"""Write graph to weighted edge list file."""Text format with one line per node listing its neighbors.
def read_adjlist(path, comments='#', delimiter=None, create_using=None, nodetype=None, encoding='utf-8'):
"""
Read graph from adjacency list file.
Parameters:
- path: File path or file handle
- comments: Character marking comment lines
- delimiter: String separating node and neighbors
- create_using: Graph constructor
- nodetype: Convert nodes to this type
- encoding: Text encoding
Returns:
NetworkX graph
"""
def write_adjlist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
"""Write graph to adjacency list file."""
def read_multiline_adjlist(path, comments='#', delimiter=None, create_using=None, nodetype=None, edgetype=None, encoding='utf-8'):
"""Read graph from multiline adjacency list file."""
def write_multiline_adjlist(G, path, delimiter=' ', comments='#', encoding='utf-8'):
"""Write graph to multiline adjacency list file."""XML-based format supporting rich graph, node, and edge attributes.
def read_graphml(path, node_type=str, edge_key_type=str, encoding='utf-8'):
"""
Read graph from GraphML file.
Parameters:
- path: File path or file handle
- node_type: Convert node IDs to this type
- edge_key_type: Convert edge keys to this type (for multigraphs)
- encoding: Text encoding
Returns:
NetworkX graph with attributes preserved
"""
def write_graphml(G, path, encoding='utf-8', prettyprint=True, infer_numeric_types=False, named_key_ids=False, edge_id_from_attribute=None):
"""Write graph to GraphML file."""
def write_graphml_xml(G, path, encoding='utf-8', prettyprint=True, infer_numeric_types=False, named_key_ids=False, edge_id_from_attribute=None):
"""Write graph to GraphML XML format."""
def parse_graphml(graphml_string, node_type=str, edge_key_type=str):
"""Parse GraphML from string."""Graph Modeling Language, a text-based format with hierarchical structure.
def read_gml(path, label='label', destringizer=None, encoding='utf-8'):
"""
Read graph from GML file.
Parameters:
- path: File path or file handle
- label: If not None, node attribute for node labels
- destringizer: Function to convert string values
- encoding: Text encoding
Returns:
NetworkX graph
"""
def write_gml(G, path, stringizer=None):
"""Write graph to GML file."""
def parse_gml(lines, label='label', destringizer=None):
"""Parse GML from lines of text."""
def generate_gml(G, stringizer=None):
"""Generate GML representation of graph."""Graph Exchange XML Format supporting dynamic graphs and visualization.
def read_gexf(path, node_type=None, relabel=False, version='1.2draft', encoding='utf-8'):
"""
Read graph from GEXF file.
Parameters:
- path: File path or file handle
- node_type: Convert node IDs to this type
- relabel: If True, relabel nodes to integers
- version: GEXF file version
- encoding: Text encoding
Returns:
NetworkX graph
"""
def write_gexf(G, path, encoding='utf-8', prettyprint=True, version='1.2draft'):
"""Write graph to GEXF file."""
def relabel_gexf_graph(G):
"""Relabel graph nodes to be suitable for GEXF."""Format used by Pajek software for large network analysis.
def read_pajek(path, encoding='UTF-8'):
"""
Read graph from Pajek file.
Parameters:
- path: File path or file handle
- encoding: Text encoding
Returns:
NetworkX graph with node and edge attributes
"""
def write_pajek(G, path, encoding='UTF-8'):
"""Write graph to Pajek file."""
def parse_pajek(lines):
"""Parse Pajek format from lines of text."""
def generate_pajek(G):
"""Generate Pajek representation of graph."""Format used by LEDA (Library of Efficient Data types and Algorithms).
def read_leda(path, encoding='utf-8'):
"""
Read graph from LEDA file.
Parameters:
- path: File path or file handle
- encoding: Text encoding
Returns:
NetworkX graph
"""
def write_leda(G, path, encoding='utf-8'):
"""Write graph to LEDA file."""
def parse_leda(lines):
"""Parse LEDA format from lines."""Compact binary formats for simple graphs.
def read_graph6(path):
"""
Read graphs from Graph6 file.
Parameters:
- path: File path or file handle
Returns:
Generator of NetworkX graphs
"""
def write_graph6(G, path, nodes=None, header=True):
"""Write graph to Graph6 file."""
def from_graph6_bytes(string):
"""Create graph from Graph6 byte string."""
def to_graph6_bytes(G, nodes=None, header=True):
"""Convert graph to Graph6 byte string."""
def read_sparse6(path):
"""Read graphs from Sparse6 file."""
def write_sparse6(G, path, nodes=None, header=True):
"""Write graph to Sparse6 file."""
def from_sparse6_bytes(string):
"""Create graph from Sparse6 byte string."""
def to_sparse6_bytes(G, nodes=None, header=True):
"""Convert graph to Sparse6 byte string."""Native Python serialization for complete graph preservation.
def read_gpickle(path):
"""
Read graph from Python pickle file.
Parameters:
- path: File path or file handle
Returns:
NetworkX graph with all attributes preserved
"""
def write_gpickle(G, path, protocol=2):
"""Write graph to Python pickle file."""JavaScript Object Notation format for web applications.
def node_link_data(G, attrs=None):
"""
Convert graph to node-link JSON format.
Parameters:
- G: NetworkX graph
- attrs: Dictionary of node/edge/graph attribute names
Returns:
Dictionary in node-link format suitable for JSON
"""
def node_link_graph(data, directed=False, multigraph=True, attrs=None):
"""Create graph from node-link JSON data."""
def adjacency_data(G, attrs=None):
"""Convert graph to adjacency JSON format."""
def adjacency_graph(data, directed=False, multigraph=True, attrs=None):
"""Create graph from adjacency JSON data."""
def tree_data(G, root, attrs=None, ident='id', children='children'):
"""Convert tree to nested JSON format."""
def tree_graph(data, attrs=None, ident='id', children='children'):
"""Create tree from nested JSON data."""Geographic format for spatial networks.
def read_shp(path, simplify=True, geom_attrs=True, strict=True):
"""
Read graph from ESRI Shapefile.
Parameters:
- path: Path to shapefile
- simplify: If True, simplify linestring geometry
- geom_attrs: Include geometry as node/edge attributes
- strict: If True, raise exception on geometry errors
Returns:
NetworkX graph with geographic coordinates
"""
def write_shp(G, outdir):
"""Write graph to ESRI Shapefile format."""import networkx as nx
# Create sample graph
G = nx.karate_club_graph()
# Write to different formats
nx.write_edgelist(G, "karate.edgelist")
nx.write_adjlist(G, "karate.adjlist")
nx.write_gml(G, "karate.gml")
nx.write_graphml(G, "karate.graphml")
nx.write_pajek(G, "karate.net")
# Read back from files
G1 = nx.read_edgelist("karate.edgelist", nodetype=int)
G2 = nx.read_adjlist("karate.adjlist", nodetype=int)
G3 = nx.read_gml("karate.gml")
G4 = nx.read_graphml("karate.graphml")
G5 = nx.read_pajek("karate.net")
print(f"Original: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
print(f"Edgelist: {G1.number_of_nodes()} nodes, {G1.number_of_edges()} edges")
print(f"GML: {G3.number_of_nodes()} nodes, {G3.number_of_edges()} edges")import networkx as nx
# Create graph with attributes
G = nx.Graph()
G.graph['name'] = 'Sample Network'
G.graph['created'] = '2024'
G.add_node(1, name='Alice', age=25, city='New York')
G.add_node(2, name='Bob', age=30, city='Boston')
G.add_node(3, name='Charlie', age=35, city='Chicago')
G.add_edge(1, 2, weight=0.8, relationship='friend', since=2020)
G.add_edge(2, 3, weight=0.6, relationship='colleague', since=2021)
G.add_edge(1, 3, weight=0.4, relationship='acquaintance', since=2022)
# Save to formats that preserve attributes
nx.write_gml(G, "network_with_attrs.gml")
nx.write_graphml(G, "network_with_attrs.graphml")
nx.write_gpickle(G, "network_with_attrs.pickle")
# Read back and verify attributes are preserved
G_gml = nx.read_gml("network_with_attrs.gml")
G_graphml = nx.read_graphml("network_with_attrs.graphml")
G_pickle = nx.read_gpickle("network_with_attrs.pickle")
print("GML graph attributes:", G_gml.graph)
print("GML node 1 attributes:", G_gml.nodes[1])
print("GML edge (1,2) attributes:", G_gml[1][2])
print("GraphML node types:", [type(n) for n in G_graphml.nodes()])
print("Pickle preserves exact types:", [type(n) for n in G_pickle.nodes()])import networkx as nx
import json
# Create graph
G = nx.karate_club_graph()
# Add some attributes
for node in G.nodes():
G.nodes[node]['group'] = 'A' if G.degree(node) > 5 else 'B'
# Convert to JSON formats
node_link_data = nx.node_link_data(G)
adjacency_data = nx.adjacency_data(G)
# Save as JSON files
with open('karate_nodelink.json', 'w') as f:
json.dump(node_link_data, f, indent=2)
with open('karate_adjacency.json', 'w') as f:
json.dump(adjacency_data, f, indent=2)
# Read back from JSON
with open('karate_nodelink.json', 'r') as f:
data = json.load(f)
G_nodelink = nx.node_link_graph(data)
with open('karate_adjacency.json', 'r') as f:
data = json.load(f)
G_adjacency = nx.adjacency_graph(data)
print(f"Node-link format: {G_nodelink.number_of_nodes()} nodes")
print(f"Adjacency format: {G_adjacency.number_of_nodes()} nodes")
print("Node attributes preserved:", G_nodelink.nodes[0])import networkx as nx
import numpy as np
# Create weighted graph
G = nx.complete_graph(5)
for (u, v) in G.edges():
G[u][v]['weight'] = np.random.random()
# Write weighted edge list
nx.write_weighted_edgelist(G, "weighted_complete.edgelist")
# Examine the file format
with open("weighted_complete.edgelist", 'r') as f:
print("First few lines of weighted edge list:")
for i, line in enumerate(f):
print(line.strip())
if i >= 5:
break
# Read back weighted graph
G_weighted = nx.read_weighted_edgelist("weighted_complete.edgelist", nodetype=int)
print(f"Loaded graph: {G_weighted.number_of_nodes()} nodes, {G_weighted.number_of_edges()} edges")
# Verify edge weights
edge = list(G_weighted.edges())[0]
print(f"Sample edge {edge} weight: {G_weighted[edge[0]][edge[1]]['weight']}")import networkx as nx
# Create larger graph
G = nx.erdos_renyi_graph(1000, 0.01, seed=42)
# Compare file sizes and speeds for different formats
import time
import os
formats = [
('edgelist', nx.write_edgelist, nx.read_edgelist),
('adjlist', nx.write_adjlist, nx.read_adjlist),
('gpickle', nx.write_gpickle, nx.read_gpickle),
('gml', nx.write_gml, nx.read_gml)
]
for name, write_func, read_func in formats:
filename = f"large_graph.{name}"
# Time writing
start = time.time()
if name == 'gml':
write_func(G, filename)
else:
write_func(G, filename)
write_time = time.time() - start
# Get file size
file_size = os.path.getsize(filename)
# Time reading
start = time.time()
if name in ['edgelist', 'adjlist']:
G_read = read_func(filename, nodetype=int)
else:
G_read = read_func(filename)
read_time = time.time() - start
print(f"{name:10} | Size: {file_size:8d} bytes | "
f"Write: {write_time:.3f}s | Read: {read_time:.3f}s")import networkx as nx
# Create several small graphs
graphs = [
nx.complete_graph(5),
nx.cycle_graph(6),
nx.path_graph(8),
nx.star_graph(4)
]
# Write to Graph6 format (one file, multiple graphs)
nx.write_graph6(graphs, "small_graphs.g6")
# Read all graphs back
graphs_read = list(nx.read_graph6("small_graphs.g6"))
print(f"Wrote {len(graphs)} graphs, read {len(graphs_read)} graphs")
# Compare individual graphs
for i, (orig, read) in enumerate(zip(graphs, graphs_read)):
print(f"Graph {i}: Original {orig.number_of_edges()} edges, "
f"Read {read.number_of_edges()} edges, "
f"Isomorphic: {nx.is_isomorphic(orig, read)}")
# Show compact representation
with open("small_graphs.g6", 'r') as f:
print("\nGraph6 file content:")
print(f.read())Install with Tessl CLI
npx tessl i tessl/pypi-networkx