无法通过打印语句写入文件

-1 投票
1 回答
1251 浏览
提问于 2025-04-18 04:08

我这里写了一个简单的程序,用来处理一个文本文件,这个文件里包含了一些细菌基因的信息,还有这些基因对应的氨基酸(直接使用更好,对吧?)。我主要依赖Biopython这个模块。

这个程序在我的Python环境中运行得很好,但我就是无法把结果保存到一个文件里。

这个代码可以正常工作:

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 个回答

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 需要一个字符串作为写入的内容。

使用上下文管理器来做同样的事情(这看起来是最符合Python风格的写法,建议你学习这个模式):

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

你也可以使用所谓的打印尖括号语法(适用于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)

撰写回答