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
这是我的第一个 post 所以如果有什么不对的地方请告诉我。
- 也许是因为
name
变量?您删除了 5 个字符,但只想删除 4 个:name = str(i[0:-4])
- 与你的问题无关,最后3行没用。你可以删除它们。
continue
else:
continue
- 尝试 运行 对无法正常工作的给定文件了解问题所在,而不是循环处理每个文件。
我尝试了 运行 以下代码。代码应该从目录中读取 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
这是我的第一个 post 所以如果有什么不对的地方请告诉我。
- 也许是因为
name
变量?您删除了 5 个字符,但只想删除 4 个:name = str(i[0:-4])
- 与你的问题无关,最后3行没用。你可以删除它们。
continue
else:
continue
- 尝试 运行 对无法正常工作的给定文件了解问题所在,而不是循环处理每个文件。