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


Python os.DirEntry.path用法及代碼示例

Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。

os.scandir()os模塊產量的方法os.DirEntry與指定路徑給定目錄中的條目相對應的對象。os.DirEntry對象具有各種屬性和方法,用於公開目錄條目的文件路徑和其他文件屬性。

path的屬性os.DirEntry對象用於獲取條目的完整路徑名。僅當os.scandir()方法中使用的path參數為絕對路徑時,完整路徑才為絕對路徑。另外,如果os.scandir()方法的路徑參數是文件描述符,則os.DirEntry.path屬性與os.DirEntry.name屬性。



注意: os.DirEntry打算在迭代後使用和丟棄對象,因為對象的屬性和方法將其值緩存起來,而不再重新獲取這些值。自調用os.scandir()方法以來,文件的元數據是否已更改,或者是否經過了很長時間。我們將不會獲得up-to-date信息。

用法: os.DirEntry.path

參數:沒有

返回值:如果os.scandir()路徑參數為bytes,則此屬性返回一個字節值,否則返回代表條目的完整路徑的字符串值。

代碼1:用於os.DirEntry.path屬性

# Python program to explain os.DirEntry.path attribute  
  
# importing os module   
import os 
  
# Directory to be scanned 
# Current working directory 
path = os.getcwd() 
  
# Using os.scandir() method 
# scan the specified directory 
# and yield os.DirEntry object 
# for each file and sub-directory 
  
print("Full path of all directory entry in '% s':" % path)  
with os.scandir(path) as itr:
    for entry in itr:
        # Exclude the entry name 
        # starting with '.'   
        if not entry.name.startswith('.'):
            # print entry's name 
            # and its full path  
            print(entry.name, ":", entry.path)
輸出:
Full path of all directory entry in '/home/ihritik':
Public:/home/ihritik/Public
Desktop:/home/ihritik/Deskop
R:/home/ihritik/R
foo.txt:/home/ihritik/foo.txt
graph.cpp:/home/ihritik/graph.cpp
tree.cpp:/home/ihritik/tree.cpp
Pictures:/home/ihritik/Pictures
abc.py:/home/ihritik/abc.py
file.txt:/home/ihritik/file.txt
Videos:/home/ihritik/Videos
images:/home/ihritik/images
Downloads:/home/ihritik/Downloads
GeeksforGeeks:/home/ihritik/GeeksforGeeks
Music:/home/ihritik/Music
Documents:/home/ihritik/Documents

參考文獻: https://docs.python.org/3/library/os.html#os.DirEntry.path




相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.DirEntry.path attribute。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。