NetworkX

Previous topic

networkx.write_adjlist

Next topic

networkx.write_multiline_adjlist

networkx.read_multiline_adjlist

read_multiline_adjlist(path, comments='#', delimiter=' ', create_using=None, nodetype=None, edgetype=None)

Read graph in multi-line adjacency list format from path.

Examples

>>> G=nx.path_graph(4)
>>> nx.write_multiline_adjlist(G,"test.adjlist")
>>> G=nx.read_multiline_adjlist("test.adjlist")

path can be a filehandle or a string with the name of the file.

>>> fh=open("test.adjlist")
>>> G=nx.read_multiline_adjlist(fh)

Filenames ending in .gz or .bz2 will be compressed.

>>> nx.write_multiline_adjlist(G,"test.adjlist.gz")
>>> G=nx.read_multiline_adjlist("test.adjlist.gz")

nodetype is an optional function to convert node strings to nodetype

For example

>>> G=nx.read_multiline_adjlist("test.adjlist", nodetype=int)

will attempt to convert all nodes to integer type

Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.)

edgetype is a function to convert edge data strings to edgetype

>>> G=nx.read_multiline_adjlist("test.adjlist")

create_using is an optional networkx graph type, the default is Graph(), a simple undirected graph

>>> G=nx.read_multiline_adjlist("test.adjlist", create_using=nx.DiGraph())

The comments character (default=’#’) at the beginning of a line indicates a comment line.

The entries are separated by delimiter (default=’ ‘). If whitespace is significant in node or edge labels you should use some other delimiter such as a tab or other symbol.

Example multiline adjlist file format

No edge data:

# source target for Graph or DiGraph
a 2
b
c
d 1
e

With edge data::

# source target for XGraph or XDiGraph with edge data
a 2
b edge-ab-data
c edge-ac-data
d 1
e edge-de-data

Reading the file will use the default text encoding on your system. It is possible to read files with other encodings by opening the file with the codecs module. See doc/examples/unicode.py for hints.

>>> import codecs
>>> fh=codecs.open("test.adjlist",'r',encoding='utf=8') # utf-8 encoding
>>> G=nx.read_multiline_adjlist(fh)