简体   繁体   中英

Python for loop not running in one script, but works in another

I have two almost identical codes. The only difference is that one code uses argparse, so that it can be run from the command line, as shown below:

parser = argparse.ArgumentParser()
parser.add_argument('directory', help = 'Main Directory of Files')
parser.add_argument('chip_num', help = 'Chip Number')
args = parser.parse_args()

path = args.directory
chip_num = args.chip_num

The other code simply defines path and chip_num as variables that i write into the script.

I have the following code below that traverses through subfolders in the directory (edited for length, but giving the main picture).

for root, dirs, files in os.walk(path):     
for d in dirs:
    if d.startswith('pass') or d.startswith('fail'):
        new_txt = 'Chip%s%s.txt' % (chip_num, d)
        path_new = os.path.join(results_dir, new_txt)

        tot_qscore = 0
        tot_reads = 0

        with open(path_new, 'w') as myfile:                
            myfile.write('File Name \t')
            ## writes other titles

        for rootfolder, blankdirs, fast5files in os.walk(d):        
            for filename in fast5files:
                if filename.endswith('.fast5'):
                    filepath = os.path.join(rootfolder, filename) 
                    with h5py.File(filepath, 'r') as hdf:                               
                        with open(path_new, 'a') as myfile:                                   
                            myfile.write('%s \t' % (filename))
                            ## gets other variables and prints it to the file
                            tot_qscore += qscore
                            tot_reads += 1

        avg_qscore = float(tot_qscore / tot_reads)

While the code runs perfectly in the script where I write in the variables, the script that can be used with the the command line is able to run the script but somehow bypasses the for loop that traverses through the 'd' directory (for rootfolder, blankdirs, fast5files in os.walk(d)) and goes right into calculating the avg_qscore, therefore giving me the error that I'm dividing by zero since tot_reads is not increasing.

Is there any reason it's skipping the for loop...is it affected by the argparse?

So the problem with the code was that I could run it under Canopy if my working directory was the one I wanted to use, but not if the working directory was different or if I was in the command line. I ended up just changing the working directory in my code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM