简体   繁体   English

Python脚本遍历整个文件夹但跳过文件夹中的文件

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

I tried running the following code.我尝试运行以下代码。 The code should read hdf5 files from a directory and create for every hdf5 file a png and a txt file with the same name (btw. I need it as input for the CNN YOLO).代码应该从目录中读取 hdf5 文件,并为每个 hdf5 文件创建一个 png 和一个同名的 txt 文件(顺便说一句。我需要它作为 CNN YOLO 的输入)。 The code does what I described but only for 20 images!该代码执行我所描述的但仅适用于 20 张图像! I added print(i) to see if the for-loop is working proper... and it is.我添加了 print(i) 以查看 for 循环是否正常工作......并且确实如此。 It prints every file in the directory (over 200 files).它打印目录中的每个文件(超过 200 个文件)。 But it just creates 20 .png and 20 .txt files.但它只创建了 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

This is my first post so if something isn't proper please let me know.这是我的第一篇文章,所以如果有什么不妥,请告诉我。

  1. Maybe it's because of the name variable?也许是因为name变量? You remove 5 characters but you want to remove only 4: name = str(i[0:-4])您删除了 5 个字符,但您只想删除 4 个: name = str(i[0:-4])
  2. Not related to your question, the last 3 lines are useless.与您的问题无关,最后 3 行没用。 you can remove them.你可以删除它们。
            continue
        else:
            continue
  1. Try to run on a given file that is not working to understand what the problem is instead of looping on each of them.尝试在无法理解问题所在的给定文件上运行,而不是在每个文件上循环。

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

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