Python| os.scandir() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.scandir()方法用于获取os.DirEntry对象的迭代器,该对象对应于指定路径给定的目录中的条目。
条目以任意顺序产生,特殊条目“。”和'..'不包括在内。
Syntax: os.scandir(path = ‘.’)
Parameter:
path: A path-like object representing the file system path. This specify the directory to be scanned. If path is not specified then current working directory is used as path.
A path-like object is a string or bytes object which represents a path.
Return Type: This method returns an iterator of os.DirEntry objects corresponding to the entries in the given directory.
代码: os.scandir()方法的使用
Python3
# Python program to explain os.scandir() method
# importing os module
import os
# Directory to be scanned
path = '/home/ihritik'
# Scan the directory and get
# an iterator of os.DirEntry objects
# corresponding to entries in it
# using os.scandir() method
obj = os.scandir(path)
# List all files and directories
# in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj :
if entry.is_dir() or entry.is_file():
print(entry.name)
# entry.is_file() will check
# if entry is a file or not and
# entry.is_dir() method will
# check if entry is a
# directory or not.
# To Close the iterator and
# free acquired resources
# use scandir.close() method
obj.close()
# scandir.close() method is called automatically
# when the iterator is exhausted
# or garbage collected, or
# when an error happens during iterating.
Files and Directories in '/home':
GeeksforGeeks
Videos
Downloads
Pictures
Documents
sample.txt
Public
Desktop
Images
R
参考: https://docs。 Python.org/3/library/os.html#os.scandir