簡體   English   中英

Python腳本遍歷整個文件夾但跳過文件夾中的文件

[英]Python script iterates over whole folder but skips files in the folder

我嘗試運行以下代碼。 代碼應該從目錄中讀取 hdf5 文件,並為每個 hdf5 文件創建一個 png 和一個同名的 txt 文件(順便說一句。我需要它作為 CNN YOLO 的輸入)。 該代碼執行我所描述的但僅適用於 20 張圖像! 我添加了 print(i) 以查看 for 循環是否正常工作......並且確實如此。 它打印目錄中的每個文件(超過 200 個文件)。 但它只創建了 20 個 .png 和 20 個 .txt 文件。

def process_fpath(path1, path2):
    sensor_dim = (101, 101)
    onlyfiles = [f for f in os.listdir(path1) if isfile(join(path1, f))]

    for i in onlyfiles:
        if i.endswith(".hdf"):
            print(i)
            #cut ".hdf"
            name = str(i[0:-5]) 
            # create png
            im = h5py.File(path1 + str(i), 'r')
            labels_im = im['labels']
            image = im['image']
            plt.imsave(path2 + name + '.png', image)
            
            # create txt
            exp = np.column_stack((np.zeros(np.size(labels_im,0)) , labels_im[:,0]/sensor_dim[0], labels_im[:,1]/sensor_dim[1], labels_im[:,3]/sensor_dim[0], labels_im[:,3]/sensor_dim[0]))
            np.savetxt(path2 + name + '.txt', exp, delimiter = '  ', fmt=['%d', '%8f', '%8f', '%8f', '%8f'])

            continue
        else:
            continue

這是我的第一篇文章,所以如果有什么不妥,請告訴我。

  1. 也許是因為name變量? 您刪除了 5 個字符,但您只想刪除 4 個: name = str(i[0:-4])
  2. 與您的問題無關,最后 3 行沒用。 你可以刪除它們。
            continue
        else:
            continue
  1. 嘗試在無法理解問題所在的給定文件上運行,而不是在每個文件上循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM