Redirect the result to a text file in python
1
0
Entering edit mode
7.0 years ago
horsedog ▴ 60

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 • 3.3k views
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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
ADD REPLY
0
Entering edit mode

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...

ADD REPLY
0
Entering edit mode
7.0 years ago

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()
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY

Login before adding your answer.

Traffic: 2702 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6