Python| os.DirEntry.is_dir() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
os 模块的os.scandir()
方法产生os.DirEntry
对象,对应于指定路径给定的目录中的条目。 os.DirEntry
对象具有各种属性和方法,用于暴露目录条目的文件路径和其他文件属性。
os.DirEntry
对象上的is_dir()
方法用于检查条目是否为目录。
注意: os.DirEntry
对象旨在在迭代后使用和丢弃,因为对象的属性和方法会缓存它们的值并且永远不会再次重新获取值。如果文件的元数据已更改,或者自调用os.scandir()方法以来已经过去了很长时间。我们不会获得最新信息。
Syntax: os.DirEntry.is_dir(*, follow_symlinks = True)
Parameter:
follow_symlinks: A boolean value is required for this parameter. If the entry is a symbolic link and follow_symlinks is True then the method will operate on the path symbolic link point to. If the entry is a symbolic link and follow_symlinks is False then the method will operate on the symbolic link itself. If the entry is not a symbolic link then follow_symlinks parameter is ignored. The default value of this parameter is True.
Return value: This method returns True if the entry is a directory otherwise returns False.
代码 #1:使用os.DirEntry.is_dir()
方法
# Python program to explain os.DirEntry.is_dir() method
# importing os module
import os
# Directory to be scanned
# Path
path = "/home / ihritik"
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
with os.scandir(path) as itr:
for entry in itr :
# Check if the entry
# is directory
if entry.is_dir() :
print("% s is a directory." % entry.name)
else:
print("% s is not a directory." % entry.name)
file.txt is not a directory.
Public is a directory.
Desktop is a directory.
R is a directory.
Music is a directory.
Documents is a directory.
tree.cpp is not a directory.
graph.cpp is not a directory.
Pictures is a directory.
GeeksForGeeks is a directory.
Videos is a directory.
images is a directory.
Downloads is a directory.
abc.txt is not a directory.
代码 #2:使用os.DirEntry.is_dir()
方法
# Python program to explain os.DirEntry.is_dir() method
# importing os module
import os
# Directory to be scanned
# Path
path = "/home / ihritik"
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
print("List of all directories in '% s':" % path)
with os.scandir(path) as itr:
for entry in itr :
# Check if the entry
# is directory
if entry.is_dir() :
# Exclude the directory name
# starting with '.'
if not entry.name.startswith('.') :
# Print Directory name
print(entry.name)
List of all directories in path '/home/ihritik':
Public
Desktop
R
Music
Documents
Pictures
GeeksForGeeks
Videos
images
Downloads
参考资料: https://docs。 Python.org/3/library/os.html#os.DirEntry.is_dir