繁体   English   中英

Python for loop不是在一个脚本中运行,而是在另一个脚本中运行

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

我有两个几乎相同的代码。 唯一的区别是一个代码使用argparse,因此可以从命令行运行它,如下所示:

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

其他代码只是将path和chip_num定义为我写入脚本的变量。

我下面有以下代码遍历目录中的子文件夹(已编辑长度,但给出了主要图片)。

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)

虽然代码可以在我编写变量的脚本中完美运行,但是可以与命令行一起使用的脚本可以运行脚本,但是以某种方式绕过了遍历“ d”目录的for循环(对于root文件夹, blankdirs,位于os.walk(d)中的fast5files),然后直接计算avg_qscore,因此出现了我被除以零的错误,因为tot_reads没有增加。

是否有任何原因跳过了for循环...是否受argparse影响?

因此,代码的问题在于,如果我的工作目录是我要使用的目录,则可以在Canopy下运行它,但是如果工作目录不同或在命令行中,则不能在Canopy下运行它。 我最终只是在代码中更改了工作目录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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