简体   繁体   中英

Can't write to file with print statements

Here I have made a simple program to go through a text file containing a bunch of genes in a bacterial genome, including the amino acids that code for those genes (explicit use is better right?) I am relying heavily on modules in Biopython.

This runs fine in my Python shell, but I can't get it to save to a file.

This works:

import Bio
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SeqUtils import GC
from Bio.SeqUtils import ProtParam
for record in SeqIO.parse("RTEST.faa", "fasta"):
    identifier=record.id
    length=len(record.seq)
    print identifier, length 

but this doesnt:

import Bio
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SeqUtils import GC
from Bio.SeqUtils import ProtParam
for record in SeqIO.parse("RTEST.faa", "fasta"):
    identifier=record.id
    length=len(record.seq)
    print identifier, length >> "testing.txt"

nor this:

import Bio
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SeqUtils import GC
from Bio.SeqUtils import ProtParam
f = open("testingtext.txt", "w")
for record in SeqIO.parse("RTEST.faa", "fasta"):
    identifier=record.id
    length=len(record.seq)
    f.write(identifier, length)

nor this:

import Bio
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from Bio.SeqUtils import GC
from Bio.SeqUtils import ProtParam
f = open("testingtext.txt", "w")
for record in SeqIO.parse("RTEST.faa", "fasta"):
    identifier=record.id
    length=len(record.seq)
    f.write("len(record.seq) \n")

Your question is rather about writing to a file in general.

Few samples:

fname = "testing.txt"
lst = [1, 2, 3]
f = open(fname, "w")
  f.write("a line\n")
  f.write("another line\n")
  f.write(str(lst))
f.close()

f.write requires string as value to write.

Doing the same using context manager (this seems to be most Pythonic, learn this pattern):

fname = "testing.txt"
lst = [1, 2, 3]
with open(fname, "w") as f:
  f.write("a line\n")
  f.write("another line\n")
  f.write(str(lst))

# closing will happen automatically when leaving the "with" block
assert f.closed

You can also use so called print chevron syntax (for Python 2.x)

fname = "testing.txt"
lst = [1, 2, 3]
with open(fname, "w") as f:
  print >> f, "a line"
  print >> f, "another line"
  print >> f, lst

print does some extra things here - adding newline to the end and converting non-string values to the string.

In Python 3.x print has different syntax as it is ordinary function

fname = "testing.txt"
lst = [1, 2, 3]
with open(fname, "w") as f:
  print("a line", file=f)
  print("another line", file=f)
  print(lst, file=f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM