Python os.scandir() - 获得一个os.DirEntry对象的迭代器

Python os.scandir()方法

Python中的os.scandir()方法被用来获得一个os.DirEntry对象的迭代器,该对象对应于指定路径下的目录中的条目。

条目是以任意顺序产生的,特殊条目’.’和’.’不包括在内。

os.scandir 语法

os.scandir(path = ' . ') 

os.scandir 参数

path:表示文件系统路径的类路径对象。这将指定要扫描的目录。如果没有指定path,则使用当前工作目录作为路径。

类路径对象是一个表示路径的字符串或字节对象。

返回类型: 这个方法返回一个os.DirEntry对象的迭代器,该迭代器对应于给定目录中的条目。

os.scandir 示例1

使用 os.scandir() 方法

# 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程