如何在python中的不同文件中重定向输出

时间:2013-06-14 12:08:37

标签: python input output

我正在使用带有两个输入文件的python脚本(goodProteins.fasta和list.txt) 并将结果保存在gene.fasta输出文件中。

fasta_file = "goodProteins.fasta" # First input 
wanted_file = "list.txt" # Second input
result_file = "result.txt" # Output fasta file

wanted = set()
with open(wanted_file) as f:
    for line in f:
        line = line.strip()
        if line != "":
            wanted.add(line)

fasta_sequences = SeqIO.parse(open(fasta_file),'fasta')
with open(result_file, "w") as f:
    for seq in fasta_sequences:
        if seq.id in wanted:
            SeqIO.write([seq], f, "fasta")

但是现在我有几个列表文件(list1.txt,list100.txt等)存在于子目录'outfile'中 在当前目录中。我想一次一个地获取每个列表文件,继续执行脚本并生成相应的输出文件 (gene1.fasta,gene100.fasta)并将它们保存在一个单独的子目录'result'中。

任何帮助??

1 个答案:

答案 0 :(得分:0)

这很简单

def process(wanted_file, result_file):
    fasta_file = "goodProteins.fasta" # First input 

    wanted = set()
    with open(wanted_file) as f:
        for line in f:
            line = line.strip()
            if line != "":
                wanted.add(line)

    fasta_sequences = SeqIO.parse(open(fasta_file),'fasta')
    with open(result_file, "w") as f:
        for seq in fasta_sequences:
            if seq.id in wanted:
                SeqIO.write([seq], f, "fasta")

for i in range(100):
    wanted_file = "list" + str(i) + ".txt"
    result_file = "gene" + str(i) + ".txt"
    process(wanted_file, result_file)