首页 / PYTHON / python – 遍历目录
python – 遍历目录
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 遍历目录,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1436字,纯文字阅读大概需要3分钟。
内容图文
![python – 遍历目录](/upload/InfoBanner/zyjiaocheng/770/5469a92d0c954fbb8e58e69299051149.jpg)
我正在寻找一种方法来遍历包含100,000个文件的目录.使用os.listdir的速度很慢,因为此函数首先从整个指定路径中获取路径列表.
什么是最快的选择?
注意:投票的人从未面对过这种情况.
解决方法:
另一个问题在评论中被称为副本:
List files in a folder as a stream to begin process immediately
……但我发现这个例子半不工作.这是适用于我的固定版本:
from ctypes import CDLL, c_int, c_uint8, c_uint16, c_uint32, c_char, c_char_p, Structure, POINTER
from ctypes.util import find_library
import os
class c_dir(Structure):
pass
class c_dirent(Structure):
_fields_ = [
("d_fileno", c_uint32),
("d_reclen", c_uint16),
("d_type", c_uint8),
("d_namlen", c_uint8),
("d_name", c_char * 4096),
# proper way of getting platform MAX filename size?
# ("d_name", c_char * (os.pathconf('.', 'PC_NAME_MAX')+1) )
]
c_dirent_p = POINTER(c_dirent)
c_dir_p = POINTER(c_dir)
c_lib = CDLL(find_library("c"))
opendir = c_lib.opendir
opendir.argtypes = [c_char_p]
opendir.restype = c_dir_p
# FIXME Should probably use readdir_r here
readdir = c_lib.readdir
readdir.argtypes = [c_dir_p]
readdir.restype = c_dirent_p
closedir = c_lib.closedir
closedir.argtypes = [c_dir_p]
closedir.restype = c_int
def listdir(path):
"""
A generator to return the names of files in the directory passed in
"""
dir_p = opendir(".")
try:
while True:
p = readdir(dir_p)
if not p:
break
name = p.contents.d_name
if name not in (".", ".."):
yield name
finally:
closedir(dir_p)
if __name__ == "__main__":
for name in listdir("."):
print name
内容总结
以上是互联网集市为您收集整理的python – 遍历目录全部内容,希望文章能够帮你解决python – 遍历目录所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。