Question: Redirect the result to a text file in python
0
gravatar for horsedog
2.9 years ago by
horsedog60
horsedog60 wrote:

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 • 2.0k views
ADD COMMENTlink modified 2.9 years ago by Devon Ryan97k • written 2.9 years ago by horsedog60

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

ADD REPLYlink written 2.9 years ago by horsedog60

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

ADD REPLYlink written 2.9 years ago by Devon Ryan97k

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 REPLYlink modified 2.9 years ago • written 2.9 years ago by cpad011214k

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 REPLYlink written 2.9 years ago by WouterDeCoster44k
0
gravatar for Devon Ryan
2.9 years ago by
Devon Ryan97k
Freiburg, Germany
Devon Ryan97k wrote:

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 COMMENTlink written 2.9 years ago by Devon Ryan97k

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

ADD REPLYlink modified 2.9 years ago • written 2.9 years ago by WouterDeCoster44k

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

ADD REPLYlink written 2.9 years ago by horsedog60

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

ADD REPLYlink written 2.9 years ago by Devon Ryan97k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1716 users visited in the last hour