有什么方法可以遍历python中的输入文件列表?

时间:2019-03-02 10:55:20

标签: python sys

我正在尝试创建一个脚本,该脚本将对输入文件列表进行一定的迭代。就我而言,例如,我将拥有3个带有氨基酸序列的文件,并且我想为每个文件创建1个输出文件。我现在遇到的问题是,在处理完当前输入文件后,我不怎么使Python打开下一个输入文件。 我尽力寻找类似的问题,但没有发现任何有用的东西。

这是我的代码:

import sys
pa = "ARNDCQEGHILKMFPSTWYV"

#this part is the one that is not working for me
i=1
while i < 10000:  #my idea is to make python try open the input files and when there are no more input files he just stops 
    try:
        with open(sys.argv[i]) as f:
            print("Working with %s file" % sys.argv[i])
            aa_aa = {}
            for aa1 in pa:
                for aa2 in pa:
                    aa = aa1+aa2
                    aa_aa[aa]={}
                    for aa3 in pa:
                        for aa4 in pa:
                            aaa = aa3+aa4
                            aa_aa[aa][aaa]=0
            for line in f: 
                try:
                    for a in range(len(line)-4):
                        a21 = line[a]+line[a+1]
                        a22 = line[a+3]+line[a+4] 
                       # print(a21,a22)
                        if a21 in aa_aa:
                            aa_aa[a21][a22] +=1
                        else:
                            pass
                except:
                    pass
        matrix_name = "matrix%s.txt" % i #here I try to create a distinct file for each input file
        matrix = open(matrix_name,"w+")
        for d in aa_aa:
            for d1 in aa_aa:
                if aa_aa[d][d1] != 0:
                    r = ""
                    r = d+" "+d1+" -> "+str(aa_aa[d][d1])+"\n"   
                    matrix.write(r)
        matrix.close()
    except:
        print("No more input files")
    i+=1

欢迎提出有关如何改善我的问题,代码或其他任何方式的建议。

1 个答案:

答案 0 :(得分:0)

标准库中的fileinput模块可让您

  

在标准输入或文件列表上快速编写循环

默认情况下,它循环遍历sys.argv[1:]中的所有名称

import fileinput

if __name__ == '__main__':
    for line in fileinput.input():
        # Process the line
        print(line)

示例:

$ echo file1 > file1.txt                                             
$ echo file2 > file2.txt                                             
$ echo file3 > file3.txt   

$ python myfile.py file1.txt file2.txt file3.txt
file1

file2

file3