This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Import files in newick format with python script

Hello everyone, With my python script (below) I'm trying to read my Newick files and print out only the species name. Example, I want to type: python script.py file.nk and the output I want is species 1, species2, species 3., but somehow Tree don't want to accept my input file and I get this error message:

Traceback (most recent call last):   File "ete_test.py", line 9, in <module>
    t = Tree("contents")   File "/usr/local/lib/python2.7/dist-packages/ete3/coretype/tree.py", line 211, in __init__
    quoted_names=quoted_node_names)   File "/usr/local/lib/python2.7/dist-packages/ete3/parser/newick.py", line 249, in read_newick
    raise NewickError('Unexisting tree file or Malformed newick tree structure.') ete3.parser.newick.NewickError: Unexisting tree file or Malformed newick tree structure. You may want to check other newick loading flags like 'format' or 'quoted_node_names'.

I don't understand since I have my file in correct format. I will be really grateful for all your help.

 from ete3 import Tree
 import sys

contents = []

with open(sys.argv[1], 'r') as f:
    contents = f.read()
    print contents

t = Tree("contents")

for leaf in t:
  print leaf.name
python newick format import files

1 answer

There are a lot of mistakes in this script. First of all, you initially declare "contents" as a list, which is not needed. Second, when you try to convert it into a tree, you pass the string "contents" instead of the variable contents. Moreover, to read a tree from a file in ete3 you just need to pass the name of the file as an argument to Tree(). So, the correct script would be:

from ete3 import Tree
import sys

t = Tree(sys.argv[1])

for leaf in t:
  print leaf.name

Log in to answer this question.