A python module to read and write the Newick format
Maintained. Last release 11 months ago. Weaker on release cadence.
pip install newickpython-newick
python package to read and write the Newick format.
Reading Newick
Since Newick specifies a format for a set of trees, all functions to read Newick return
a list of newick.Node objects.
-
Reading from a string:
>>> from newick import loads >>> trees = loads('(A,B,(C,D)E)F;') >>> trees[0].name 'F' >>> [n.name for n in trees[0].descendants] ['A', 'B', 'E'] -
Reading from a
file-like object:>>> import io >>> from newick import load >>> with io.open('fname', encoding='utf8') as fp: ... trees = load(fp) -
Reading from a path:
>>> from newick import read >>> trees = read('fname') >>> import pathlib >>> trees = read(pathlib.Path('fname'))
Supported Newick dialects
While the set of reserved characters in Newick (;(),:) is relatively small, it's still often
seen as too restrictive, in particular when it comes to adding more data to tree nodes. Thus, Newick
provides two mechanisms to overcome this restriction:
- quoted labels to allow arbitrary text as node names,
- comments enclosed in square brackets.
Quoted node labels
Node labels in Newick may be quoted (i.e. enclosed in single quotes ') to make it possible to
add characters which are otherwise reserved. The newick package supports quoted labels.
>>> from newick import loads
>>> print(loads("('A:B','C''D')'E(F)'")[0].ascii_art())
┌─'A:B'
──'E(F)'─┤
└─'C''D'
When creating Newick trees programmatically, names can be quoted (if necessary) automatically: