簡體   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