以下脚本无法将所有输出打印到文件中(测试.txt),如何解决?(它只打印了一个3-mer)。你知道吗
import random
def amino(length):
return ''.join(random.choice('GPAVLIMCFYWHKRQNEDST') for i in range(length))
list_size = 8000
for j in range(list_size):
drd = int(random.normalvariate(3, 0))
f = open('gen.dat', 'w')
print amino(drd)
f.write(amino(drd))
f.close()
当您以
'w'
模式打开一个文件时,实际上您正在覆盖该文件(如果它已经存在的话)。你知道吗在循环中打开并关闭文件,因此文件将只包含最后一个
peptide(aminoacidDRG)
。您应该在循环外打开文件,并使用with
语句来处理文件,这样with
语句就可以在with
块结束后处理关闭文件的问题。你知道吗示例-
每次循环都要打开和关闭文件,只打开一次
当您用
'w'
打开一个文件时,如果该文件已经存在,它将被覆盖。您可以使用'a'
进行追加,但我建议您使用上面的代码,只打开一次文件并继续写入。您可以使用with
语句来避免关闭文件相关问题 更多 >
编程相关推荐