当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python os.DirEntry.is_dir()用法及代码示例


Python中的OS模块提供了与操作系统进行交互的函数。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。

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

is_dir()方法开启os.DirEntryobject用于检查条目是否为目录。


注意: os.DirEntry打算在迭代后使用和丢弃对象,因为对象的属性和方法将其值缓存起来,而不再重新获取这些值。自调用os.scandir()方法以来,文件的元数据是否已更改,或者是否经过了很长时间。我们将不会获得up-to-date信息。

用法: os.DirEntry.is_dir(*, follow_symlinks = True)

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

返回值:如果条目是目录,则此方法返回True,否则返回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



相关用法


注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | os.DirEntry.is_dir() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。