Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。
os.scandir()
os模塊產量的方法os.DirEntry
與指定路徑給定目錄中的條目相對應的對象。os.DirEntry
對象具有各種屬性和方法,用於公開目錄條目的文件路徑和其他文件屬性。
name
歸因於os.DirEntry
object用於獲取條目的基本文件名,相對於在os.scandir()
方法。
注意: os.DirEntry
打算在迭代後使用和丟棄對象,因為對象的屬性和方法將其值緩存起來,而不再重新獲取這些值。自調用os.scandir()方法以來,文件的元數據是否已更改,或者是否經過了很長時間。我們將不會獲得up-to-date信息。
用法: os.DirEntry.name
參數:沒有
返回值:此屬性返回一個字符串值,該字符串值表示條目的基本文件名。
代碼1:用於os.DirEntry.name
屬性
# Python program to explain os.DirEntry.name 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("Base filename 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
print(entry.name)
輸出:
Base filename of all directory entry in '/home/ihritik': Public Desktop R foo.txt graph.cpp tree.cpp Pictures abc.py file.txt Videos images Downloads GeeksforGeeks Music Documents
代碼2:用於os.DirEntry.name()
屬性
# Python program to explain os.DirEntry.name 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("All files and directory whose name starts with letter 'D' in '% s'" % path)
with os.scandir(path) as itr:
for entry in itr:
# Check if directory entry name
# starts with letter 'D'
if entry.name.startswith('D'):
# print entry's name
print(entry.name)
輸出:
All files and directory whose name starts with letter 'D' in '/home/ihritik': Desktop Documents Downloads
參考文獻: https://docs.python.org/3/library/os.html#os.DirEntry.name
相關用法
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.DirEntry.name attribute。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。