-2

I am trying to create a script that will do a certain iteration over a list of input files. In my case, I will have for example 3 files with a sequence of amino acids and I want to create 1 output file for each of the files. The problem I have now is that I do not how to make Python open the next input file after it is done with the current one. I tried my best at searching similar questions, but I did not find anything useful.

Here is my code:

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

Any suggestions on how to improve my question, code, or anything else is welcomed.

1 Answers1

0

The fileinput module in the standard library lets you

quickly write a loop over standard input or a list of files

By default it loops over all the names in sys.argv[1:]

import fileinput

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

Example:

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

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

file2

file3
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153