2017-08-10 76 views
3

在Python中检查数百万个文件路径的存在的最佳方法是什么?标识不存在的路径?我目前正在使用单线程,如下所示:检查多个文件存在的最快方法

paths_not_existing = set() 
all_file_paths = [long_list] 
for path_name in all_file_paths: 
    if os.path.isfile(path_name) == False: 
     paths_not_existing.add(path_name) 

多线程可能会加快速度吗?特别是,因为我认为这是I/O限制,我想知道是否有办法同时查找多个路径?

(在引用的情况下,我使用的硬盘不是固态硬盘)。

+0

使用解析会加快东西...... 'nonexistent_paths = {路径名的路径名在all_file_paths如果不是os.path.isfile(路径名)}'。或者过滤掉。 'nonexistent_paths = set(filter(lambda f:not os.path.isfile(f),all_file_paths))' – erip

+0

如果这些路径在树中,如果路径已经存在,也可以更有效地查找路径确定父母不存在。 –

回答

0

你当然可以使用多线程/处理,它应该给你一个加速。有很多不同的方法可以做到这一点,但最简单的方法可能是multiprocessing.Pool.map,它与Python内置的map函数的作用相同,但通过核心进行分布。

from multiprocessing import Pool 
import numpy as np 
ncores = #number of cores, e.g. 8 
pool = Pool(ncores) 

all_file_paths = np.array(long_array) 

# create a list of booleans corresponding to whether 
# each file is in your path or not. 
selector = np.array(pool.map(os.path.isfile,all_file_paths)) 

paths_not_existing = all_file_paths[selector] 
相关问题