无法使用print语句写入文件

时间:2014-04-24 20:34:49

标签: python printing biopython

在这里,我制作了一个简单的程序来浏览一个包含细菌基因组中一堆基因的文本文件,包括编码这些基因的氨基酸(显式使用更好吗?)我在很大程度上依赖于模块Biopython。

这在我的Python shell中运行良好,但我无法将其保存到文件中。

这有效:

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 

但这不是:

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"

也不是:

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)

也不是:

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")

1 个答案:

答案 0 :(得分:3)

您的问题主要是写一般文件。

几个样本:

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需要字符串作为值来写。

使用上下文管理器(这似乎是大多数Pythonic,学习这种模式):

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

你也可以使用所谓的print chevron语法(对于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在这里做了一些额外的事情 - 在结尾处添加换行符并将非字符串值转换为字符串。

在Python 3.x中,print具有不同的语法,因为它是普通函数

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)