gpt4 book ai didi

python - 部分目录列表

转载 作者:IT王子 更新时间:2023-10-29 00:35:11 28 4
gpt4 key购买 nike

是否可以获取部分目录列表?

在 Python 中,我有一个进程试图获取包含 >100,000 个文件的目录的 os.listdir,这需要很长时间。比方说,我希望能够快速获得前 1,000 个文件的列表。

我怎样才能做到这一点?

最佳答案

我找到了一个给我文件随机顺序的解决方案:)(至少我看不到模式)

首先我找到了this post in the python maillist .附加了 3 个文件,您必须将它们复制到磁盘(opendir.pyx、setup.py、test.py)。接下来你需要python包Pyrex从帖子中编译文件 opendir.pyx。我在安装 Pyrex 时遇到问题,发现我必须通过 apt-get 安装 python-dev。接下来,我使用 python setup.py install 安装了上述三个下载文件中的 opendir 包。文件 test.py 包含如何使用它的示例。

接下来我感兴趣的是这个解决方案比使用 os.listdir 快多少,我用下面的小 shellscript 创建了 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 倍,这非常好 :)。

我希望这是您努力实现的目标。

关于python - 部分目录列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170157/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com