无法使用print语句写入文件

2024-06-19 19:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这在我的pythonshell中运行得很好,但我无法将其保存到文件中。在

这是有效的:

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 

但这并不是:

^{pr2}$

也不是这个:

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

Tags: fromimportlenrecordlengthgcseqbio
1条回答
网友
1楼 · 发布于 2024-06-19 19:29:49

你的问题更像是写文件。在

少数样品:

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风格的,请学习此模式):

^{pr2}$

您还可以使用所谓的print chevron语法(对于python2.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在这里做了一些额外的工作-在末尾添加换行符并将非字符串值转换为字符串。在

在python3.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)

相关问题 更多 >