如何将数据打印到文件中?

2024-10-02 02:44:48 发布

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

以下脚本无法将所有输出打印到文件中(测试.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()

Tags: 文件inimporttxt脚本forsizedef
2条回答

当您以'w'模式打开一个文件时,实际上您正在覆盖该文件(如果它已经存在的话)。你知道吗

在循环中打开并关闭文件,因此文件将只包含最后一个peptide(aminoacidDRG)。您应该在循环外打开文件,并使用with语句来处理文件,这样with语句就可以在with块结束后处理关闭文件的问题。你知道吗

示例-

import random

def peptide(length):    
    return ''.join(random.choice('GPAVLIMCFYWHKRQNEDST') for i in range(length))

list_size = 8000
with open('gen.dat', 'w') as f:
    for j in range(list_size):    
        aminoacidDRG = int(random.normalvariate(3, 0))    
        print peptide(aminoacidDRG)        
        f.write(peptide(aminoacidDRG))

每次循环都要打开和关闭文件,只打开一次

f = open('gen.dat', 'w')  
for j in range(list_size):    
    aminoacidDRG = int(random.normalvariate(3, 0))      
    print peptide(aminoacidDRG)        
    f.write(peptide(aminoacidDRG) + '\n')
f.close()

当您用'w'打开一个文件时,如果该文件已经存在,它将被覆盖。您可以使用'a'进行追加,但我建议您使用上面的代码,只打开一次文件并继续写入。您可以使用with语句来避免关闭文件

with open('gen.dat', 'w') as f:
    for j in range(list_size):    
        aminoacidDRG = int(random.normalvariate(3, 0))      
        print peptide(aminoacidDRG)        
        f.write(peptide(aminoacidDRG) + '\n')

相关问题 更多 >

    热门问题