os.walk是否利用操作系统返回的文件类型的效率? [英] Does os.walk take advantage of the file type returned by the OS for efficiency?

查看:141
本文介绍了os.walk是否利用操作系统返回的文件类型的效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

os.walk 函数返回目录和文件的单独列表。许多常见操作系统(如Windows和Linux)上的底层操作系统调用返回一个文件类型或标志,指定每个目录条目是文件还是目录;没有这个标志,有必要再次查询每个返回的文件名的操作系统。 os.walk 的代码是否使用这些信息,或者将其抛弃为

The os.walk function returns separate lists for directories and files. The underlying OS calls on many common operating systems such as Windows and Linux return a file type or flag specifying whether each directory entry is a file or a directory; without this flag it's necessary to query the OS again for each returned filename. Does the code for os.walk make use of this information or does it throw it away as os.listdir does?

推荐答案

不,没有。

在引擎盖下, os.walk() code>使用 os.listdir() os.path.isdir()列出文件和目录分别。请参阅源代码 walk()

Under the hood, os.walk() uses os.listdir() and os.path.isdir() to list files and directories separately. See the source code of walk().

具体来说:

try:
    # Note that listdir and error are globals in this module due
    # to earlier import-*.
    names = listdir(top)
except error, err:
    if onerror is not None:
        onerror(err)
    return

dirs, nondirs = [], []
for name in names:
    if isdir(join(top, name)):
        dirs.append(name)
    else:
        nondirs.append(name)

其中 listdir isdir os.listdir() os的模块全局变量。 path.isdir()函数。它递归调用子目录。

where listdir and isdir are module globals for the os.listdir() and os.path.isdir() functions. It calls itself recursively for subdirs.

这篇关于os.walk是否利用操作系统返回的文件类型的效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆