是否可以获得部分目录列表?
在Python中,我有一个进程试图获取包含&100,000个文件的目录的os.listdir
,这需要永远。我希望能够快速获得前1,000个文件的列表。
我怎样才能做到这一点?
答案 0 :(得分:3)
我找到了一个解决方案,它给了我一个随机的文件顺序:)(至少我看不到一个模式)
首先我找到了this post in the python maillist。附加了3个文件,您必须将其复制到磁盘(opendir.pyx, setup.py, test.py
)。接下来,您需要python包Pyrex来从帖子中编译文件opendir.pyx
。我在安装Pyrex时遇到问题,发现我必须通过python-dev
安装apt-get
。接下来,我使用opendir
安装了以上三个下载文件中的python setup.py install
包。文件test.py
包含如何使用它的示例。
接下来,我感兴趣的是这个解决方案比使用os.listdir快多少,并且使用以下小shellcript创建了200000个文件。
for((i=0; i<200000; i++))
do
touch $i
done
以下脚本是我在刚创建文件的目录中运行的基准测试:
from opendir import opendir
from timeit import Timer
import os
def list_first_fast(i):
d=opendir(".")
filenames=[]
for _ in range(i):
name = d.read()
if not name:
break
filenames.append(name)
return filenames
def list_first_slow(i):
return os.listdir(".")[:i]
if __name__ == '__main__':
t1 = Timer("list_first_fast(100)", "from __main__ import list_first_fast")
t2 = Timer("list_first_slow(100)", "from __main__ import list_first_slow")
print "With opendir: ", t1.repeat(5, 100)
print "With os.list: ", t2.repeat(5, 100)
我系统的输出是:
With opendir: [0.045053958892822266, 0.04376697540283203, 0.0437769889831543, 0.04387712478637695, 0.04404592514038086]
With os.list: [9.50291895866394, 9.567682027816772, 9.865844964981079, 13.486984968185425, 9.51977801322937]
正如你所看到的,当我从200000中返回一个包含100个文件名的列表时,我获得了200倍的加速,这非常好:)。
我希望这是你想要实现的目标。