tl;博士:从 Python 3.5(目前处于测试版)开始,只需使用os.scandir
更新>
正如我之前所写,由于“iglob”只是真正迭代器的一个外观,因此您必须调用低级系统函数才能像您想要的那样一次获取一个迭代器。幸运的是,可以从 Python 调用低级函数。
Windows 和 Posix/Linux 系统的低级函数是不同的。
- 如果您使用的是 Windows,您应该检查是否
win32api
有任何调用来读取“目录中的下一个条目”或如何继续。
- 如果您使用的是 Posix/Linux,则可以直接通过 ctypes 调用 libc 函数并一次获取文件目录条目(包括命名信息)。
关于 C 函数的文档在这里:http://www.gnu.org/s/libc/manual/html_node/Opening-a-Directory.html#Opening-a-Directory http://www.gnu.org/s/libc/manual/html_node/Opening-a-Directory.html#Opening-a-Directory
http://www.gnu.org/s/libc/manual/html_node/Reading_002fClosing-Directory.html#Reading_002fClosing-Directory http://www.gnu.org/s/libc/manual/html_node/Reading_002fClosing-Directory.html#Reading_002fClosing-Directory
我提供了一段 Python 代码,演示了如何调用低级 C 函数在我的系统上但此代码片段可能不适用于您的系统[footnote-1]。我建议打开你的/usr/include/dirent.h
头文件并验证 Python 代码片段是否正确(您的 PythonStructure
必须匹配Cstruct
)在使用代码片段之前。
这是使用的片段ctypes
and libc
我已经将它们放在一起,允许您获取每个文件名并对其执行操作。注意ctypes
当你这样做时,会自动给你一个Python字符串str(...)
在结构体上定义的 char 数组上。 (我正在使用print
语句,它隐式调用Python的str
)
#!/usr/bin/env python2
from ctypes import *
libc = cdll.LoadLibrary( "libc.so.6")
dir_ = c_voidp( libc.opendir("/home/jsbueno"))
class Dirent(Structure):
_fields_ = [("d_ino", c_voidp),
("off_t", c_int64),
("d_reclen", c_ushort),
("d_type", c_ubyte),
("d_name", c_char * 2048)
]
while True:
p = libc.readdir64(dir_)
if not p:
break
entry = Dirent.from_address( p)
print entry.d_name
update:Python 3.5 现在处于测试阶段 - Python 3.5 中的新版本os.scandir
函数调用可作为具体化使用PEP 471 https://www.python.org/dev/peps/pep-0471/(“更好更快的目录迭代器”)它完全符合这里的要求,此外还有许多其他优化,可以将速度提高多达 9 倍os.listdir
Windows 下的大型目录列表(Posix 系统中增加 2-3 倍)。
[脚注-1]dirent64
C struct
在每个系统的 C 编译时确定。