Skip to main content
 首页 » 编程设计

python之从目录批量导入文件到python脚本

2024年09月07日7langtianya

我想将特定目录中的所有 jpg 图像导入到我的 python 脚本中,但不是一次全部导入,而是每次导入 500 张图像。

一种可能的解决方案如下:

from glob import glob 
 
i = 0 
batch= 500 
# Read images from file 
for filename in glob('Directory/*.jpg'): 
    i = i + 1 
    if i % batch == 0: 
        # apply an algorithm with this data-batch # 

这是正确的吗?

有没有更有效的方法来做到这一点?

请您参考如下方法:

from os import listdir 
 
directory = 'Directory/*.jpg' 
 
fnames = list(fname for fname in listdir(directory) if fname.endswith('.jpg')) 
 
batchsize = 500 
l_index, r_index = 0, batchsize 
batch = fnames[l_index:r_index] 
 
while batch: 
 
    for i in batch: 
        import_function(i)  
    l_index, r_index = r_index, r_index + batchsize 
    batch = fnames[l_index:r_index]