【问题标题】:How to loop through large amount of folder faster如何更快地遍历大量文件夹
【发布时间】:2019-09-03 14:12:48
【问题描述】:

我必须遍历给定路径 (My_Path) 的大量文件夹(大约 60 000 个)。 然后在My_Path 的每个文件夹中,我必须检查文件名是否包含某个日期。 我想知道是否有比使用os 库逐个循环更快的方法。 (约 1 小时)

My_Path:
-   Folder 1
              o File 1
              o File 2
              o File 3
              o …
-   Folder 2
-   Folder 3
-   …
-   Folder 60 000
import os
My_Path = r'\\...\...\...\...'
mylist2 = os.listdir(path)  # give a list of 60000 element
for folder in mylist2:
    mylist = os.listdir(My_Path + folder)  # give the list of all files in each folder
    for file in mylist:
        Check_Function(file)

实际运行大约需要一个小时,我想知道是否有最佳解决方案。

谢谢!!

【问题讨论】:

标签: python


【解决方案1】:

正如其他人已经建议的那样,您可以在此answer 中获取所有文件的列表lst。然后你可以使用多处理来旋转你的函数。

import multiprocessing as mp


def parallelize(fun, vec, cores):
    with mp.Pool(cores) as p:
        res = p.map(fun, vec)
    return res

然后运行

res = parallelize(Check_Function, lst, mp.cpu_count()-1)

更新 鉴于我认为 Check_Function 不受 CPU 限制,您可以使用更多内核。

【讨论】:

  • @sam 请发布您自己的替代答案。此答案不是社区 wiki 答案,您不应该做出如此严重的更改。
【解决方案2】:

试试os.walk(),可能更快:

import os
My_Path = r'\\...\...\...\...'
for path, dirs, files in os.walk(My_Path): 
    for file in files:
        Check_Function(os.path.join(path, file))

如果不是,可能是你的 Check_Function 占用了周期。

【讨论】:

  • walk 在最新版本的 Python 上使用 scandir,这 (AFAICT) 在 Windows 下的网络驱动器上应该明显更快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 2022-06-22
  • 2020-04-09
  • 2012-06-16
  • 1970-01-01
  • 2023-03-03
  • 2021-05-27
相关资源
最近更新 更多