Python os.DirEntry.is_dir()方法

Python os.DirEntry.is_dir()方法

Python os模块的os.scandir()方法产生os.DirEntry对象,对应于指定路径给出的目录中的条目。os.DirEntry对象具有各种属性和方法,用于公开目录项的文件路径和其他文件属性。

os.DirEntry对象上的is_dir()方法用于检查条目是否为目录。

注意:os.DirEntry对象的目的是在迭代后被使用和扔掉,因为对象的属性和方法缓存了它们的值,再也不会重新获取值。如果文件的元数据已经被更改,或者如果自调用os.scandir()方法以来已经经过了很长时间。我们将得不到最新的信息。

os.DirEntry.is_dir() 语法

os.DirEntry.is_dir(*, follow_symlinks = True) 

os.DirEntry.is_dir() 参数

follow_symlinks:该参数需要一个布尔值。如果条目是一个符号链接,并且follow_symlinks为True,那么该方法将对符号链接指向的路径进行操作。如果条目是一个符号链接,并且follow_symlinks为False,那么该方法将对符号链接本身进行操作。如果条目不是符号链接,则忽略follow_symlinks参数。默认值为“True”。

返回值:如果条目是目录,该方法返回True,否则返回False。

os.DirEntry.is_dir() 示例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.

os.DirEntry.is_dir() 示例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/ library/os.html#os.DirEntry.is_dir

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程