This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Redirect the result to a text file in python

Hi, I'm new to python, now I'm using python to parse my data but I have no idea how to save my print-out result in a new file. I tried some codes but the new file is empty, does anyone know? Here is my script:

with open("new_file.txt", "w") as f:
from Bio import SeqIO
for seq_record in SeqIO.parse("genome.fna", "fasta"):
   print seq_record.id, file = f)
f.close()
sequence

I mistyped, should be: print seq_record.id, file = f)

This is a known rendering issue on the site, don't worry about the missing (.

works with python3.biopython 1.7 and python 3.6:

from Bio import SeqIO
from datetime import datetime
dnafile = open("ids_"+datetime.now().strftime("%Y%m%d_%H%M%S"+".txt"), "a")
for record in SeqIO.parse("test.fa","fasta"):
    dnafile.write record.id+"\n")
dnafile.close()

(note: Bracket open is lost in forum board formatting, after dnafile.write.)

output:

$ python3 header.py 
$ cat ids_20171204_154546.txt 
seq1
seq2

Your indentation is a bit unclear, can you correct this please? I'm not close enough to a computer to figure it out but I would expect your code to work...

1 answer

If you just want to save the id, then:

from Bio import SeqIO
of = open("new_file.txt", "w")
for seq_record in SeqIO.parse("genome.fna", "fasta"):
    of.write("{}\n".formatseq_record.id))
of.close()

Note that there is here also a rendering issue: .format(seq_record

Hi , thank you very much, I tried but it says "AttributeError: 'str' object has no attribute 'formatseq_record'"

There should be a ( between format and seq in that line. It's the same rendering issue you ran into in your post.

Log in to answer this question.