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 绑定(bind),我想知道是否有办法同时查找多个路径?
(作为引用,我使用的硬盘驱动器不是固态的)。
最佳答案
你当然可以使用多线程/处理,它应该会给你一个加速。有很多不同的方法,但最简单的可能是使用 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]
关于python - 检查多个文件是否存在的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45619003/