當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。