用法:
os.scandir(path='.')返回与
path给出的目录中的条目相对应的os.DirEntry对象的迭代器。条目按任意顺序生成,不包括特殊条目'.'和'..'。如果在创建迭代器后从目录中删除或添加文件,则未指定是否包含该文件的条目。使用
scandir()而不是listdir()可以显著提高还需要文件类型或文件属性信息的代码的性能,因为如果操作系统在扫描目录时提供了这些信息,os.DirEntry对象就会公开这些信息。所有os.DirEntry方法都可以执行系统调用,但is_dir()和is_file()通常只需要对符号链接进行系统调用;os.DirEntry.stat()在 Unix 上总是需要一个系统调用,但在 Windows 上只需要一个用于符号链接。path可能是path-like 对象。如果path的类型为bytes(直接或间接通过PathLike接口),则每个os.DirEntry的name和path属性的类型将为bytes;在所有其他情况下,它们将是类型str。该函数还可以支持指定文件说明符;文件说明符必须引用一个目录。
使用参数
path引发审计事件os.scandir。scandir()迭代器支持上下文管理器协议,具有以下方法:-
scandir.close() 关闭迭代器并释放获取的资源。
当迭代器耗尽或垃圾收集时,或者在迭代过程中发生错误时,它会自动调用。但是,建议显式调用它或使用
with语句。3.6 版中的新函数。
以下示例显示了
scandir()的简单用法,以显示给定path中不以'.'开头的所有文件(不包括目录)。entry.is_file()调用通常不会进行额外的系统调用:with os.scandir(path) as it: for entry in it: if not entry.name.startswith('.') and entry.is_file(): print(entry.name)注意
在基于 Unix 的系统上,
scandir()使用系统的 opendir() 和 readdir() 函数。在 Windows 上,它使用 Win32 FindFirstFileW 和 FindNextFileW 函数。3.5 版中的新函数。
3.6 版中的新函数:增加了对上下文管理器协议和
close()方法。如果一个os.scandir迭代器既没有耗尽也没有明确关闭ResourceWarning将在其析构函数中发出。该函数接受 path-like 对象。
在 3.7 版中更改:增加了对文件说明符在 Unix 上。
-
相关用法
- Python os.scandir()用法及代码示例
- Python os.sched_setaffinity()用法及代码示例
- Python os.sched_getaffinity()用法及代码示例
- Python os.sched_get_priority_max()用法及代码示例
- Python os.sched_get_priority_min()用法及代码示例
- Python os.sched_rr_get_interval()用法及代码示例
- Python os.set_blocking()用法及代码示例
- Python os.setregid()用法及代码示例
- Python os.strerror()用法及代码示例
- Python os.spawnl用法及代码示例
- Python os.set_inheritable()用法及代码示例
- Python os.system()用法及代码示例
- Python os.setreuid()用法及代码示例
- Python os.statvfs()用法及代码示例
- Python os.symlink()用法及代码示例
- Python os.sync()用法及代码示例
- Python os.stat()用法及代码示例
- Python os.sendfile()用法及代码示例
- Python os.setgroups()用法及代码示例
- Python os.sysconf()用法及代码示例
注:本文由纯净天空筛选整理自python.org大神的英文原创作品 os.scandir。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
