Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。
os.scandir()
Python中的方法用於獲取os.DirEntry對象的迭代器,該對象與指定路徑給定目錄中的條目相對應。條目以任意順序產生,不包括特殊條目“。”和“ ..”。
用法: os.scandir(path = ‘.’)
參數:
path:代表文件係統路徑的path-like對象。這指定要掃描的目錄。如果未指定路徑,則將當前工作目錄用作路徑。
path-like對象是表示路徑的字符串或字節對象。
返回類型:此方法返回與給定目錄中的條目相對應的os.DirEntry對象的迭代器。
代碼:使用
os.scandir()
方法
# Python program to explain os.scandir() method
# importing os module
import os
# Directory to be scanned
path = '/home / ihritik'
# Scan the directiory and get
# an iterator of os.DirEntry objets
# corresponding to entries in it
# using os.scandir() method
obj = os.scandir()
# List all files and diretories
# in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj :
if entry.is_dir() or entry.is_file():
print(entry.name)
# entry.is_file() will check
# if entry is a file or not and
# entry.is_dir() method will
# check if entry is a
# directory or not.
# To Close the iterator and
# free acquired resources
# use scandir.close() method
obj.close()
# scandir.close() method is called automatically
# when the iterator is exhausted
# or garbage collected, or
# when an error happens during iterating.
輸出:
Files and Directories in '/home': GeeksforGeeks Videos Downloads Pictures Documents sample.txt Public Desktop Images R
參考: https://docs.python.org/3/library/os.html#os.scandir
相關用法
- Python os.dup()用法及代碼示例
- Python next()用法及代碼示例
- Python set()用法及代碼示例
- Python object()用法及代碼示例
- Python bytes()用法及代碼示例
- Python os.times()用法及代碼示例
- Python os.chmod用法及代碼示例
- Python hash()用法及代碼示例
- Python os.ftruncate()用法及代碼示例
- Python os.truncate()用法及代碼示例
- Python os.fsdecode()用法及代碼示例
- Python dict pop()用法及代碼示例
- Python os.abort()用法及代碼示例
- Python os.WEXITSTATUS()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.scandir() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。