[英]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:
唯一的区别是一个代码使用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
The other code simply defines path and chip_num as variables that i write into the script. 其他代码只是将path和chip_num定义为我写入脚本的变量。
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. 虽然代码可以在我编写变量的脚本中完美运行,但是可以与命令行一起使用的脚本可以运行脚本,但是以某种方式绕过了遍历“ d”目录的for循环(对于root文件夹, blankdirs,位于os.walk(d)中的fast5files),然后直接计算avg_qscore,因此出现了我被除以零的错误,因为tot_reads没有增加。
Is there any reason it's skipping the for loop...is it affected by the argparse? 是否有任何原因跳过了for循环...是否受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. 因此,代码的问题在于,如果我的工作目录是我要使用的目录,则可以在Canopy下运行它,但是如果工作目录不同或在命令行中,则不能在Canopy下运行它。 I ended up just changing the working directory in my code.
我最终只是在代码中更改了工作目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.