如何在 Python 中列出目錄的內容?
計算機的檔案系統的目錄是一種用於儲存和查詢檔案的組織功能。透過分層組織目錄來建立目錄樹。目錄中存在父子關係。資料夾也可以用來指代目錄。隨著時間的推移,Python 積累了許多可以列出目錄內容的 API。有用的函式包括 Path.iterdir、os.scandir、os.walk、Path.rglob 和 os.listdir。
在 Python 中,我們可能需要給定目錄中的檔案或資料夾列表。您可以透過多種方式實現此目的。
OS 模組
Python 的 OS 模組中提供了一個函式,該函式返回目錄中檔案或資料夾的列表。
使用 Python 作業系統庫列出目錄中的檔案。Python os.listdir() 方法列出目錄中的每個檔案和資料夾。函式 os.walk() 返回整個檔案樹中所有檔案的列表。
使用 Python OS 庫列出目錄中的檔案有多種方法。
本文將介紹如何使用 os.listdir() 獲取目錄中的檔案和資料夾。
使用 os.listdir() 方法
Python 中的 os.listdir() 方法顯示指定目錄中所有檔案和資料夾的列表。作業系統採用像 "." 和 ".." 這樣的特殊條目在不同目錄之間遍歷,但此方法不會返回這些條目。
此外,os.listdir() 不會返回第一級目錄以上的檔案和資料夾。換句話說,os.listdir() 不會返回從該方法找到的子資料夾中的任何內容。os.listdir() 函式只接受一個引數,即要從中檢索其檔案和資料夾名稱的目錄的檔案路徑。
語法
os.listdir(path)
示例
以下是如何使用 os.listdir() 方法列出目錄內容的示例 -
# importing the module import os # Providing the path of the directory path = 'D:\Work TP' # Retrieving the list of all the files folders = os.listdir(path) # loop to iterate every item in the list for s in folders: print(s)
輸出
以下是上述程式碼的輸出 -
moving files.py mysql_access.py stored procedure python-sql.py trial.py
使用 os.walk() 方法
可以使用 os.walk() 函式獲取樹中包含的檔案列表。該技術遍歷樹中的每個目錄。
然後,os.walk() 返回目錄和任何子目錄中包含的所有檔案和資料夾的名稱。
語法
os.walk(topdown)
如果 topdown 設定為 True,則表示應從上到下掃描目錄。如果此值為 False(可選),則將從下到上掃描目錄。
示例
以下是如何使用 os.walk() 方法列出目錄內容的示例
# importing the module import os # Providing the path path = 'D:\Work TP' # loop for retrieving all the files and folders for top-down search for root, directories, contents in os.walk(path, topdown=False): # joining together the root folder where the directory exists of every files along with its name for name in contents: print(os.path.join(root, name)) for name in directories: print(os.path.join(root, name))
輸出
以下是上述程式碼的輸出 -
D:\Work TP\SubDirectory\How to copy files from one folder to another using Python.docx D:\Work TP\SubDirectory\How to create an empty file using Python.docx D:\Work TP\SubDirectory\Sarika Sample Articles (Python-MySQL Procedures).docx D:\Work TP\SubDirectory\sql python create table.docx D:\Work TP\moving files.py D:\Work TP\mysql_access.py D:\Work TP\stored procedure python-sql.py D:\Work TP\trial.py D:\Work TP\SubDirectory
使用 os.scandir() 方法
Scandir 使用與 listdir 相同的目錄迭代系統呼叫來獲取指定路徑上檔案的名稱,但它在兩個方面與 listdir 不同。
- 返回輕量級 DirEntry 物件而不是裸檔名字串,這些物件包含檔名字串並提供簡單的獲取作業系統可能返回的任何其他資料的方法。
- 與返回整個列表相反,scandir 透過返回生成器而不是列表來充當真正的迭代器。
對於路徑中的每個檔案和子目錄,scandir() 返回一個 DirEntry 物件。
示例
以下是如何使用 os.scandir() 方法列出目錄內容的示例 -
# importing the modules import os # getting all the files present inside a specific folder dir_track = r'D:\Work TP' for track in os.scandir(dir_track): if track.is_file(): print(track.name)
輸出
以下是上述程式碼的輸出 -
moving files.py mysql_access.py stored procedure python-sql.py trial.py
glob 模組
Python glob 模組允許我們搜尋所有路徑名,以查詢符合給定模式的檔案。用於定義提供的檔案匹配模式的規則與 Unix shell 中建立的規則相同。
該軟體的輸出以隨機順序返回遵循這些準則以進行特定模式檔案匹配而獲得的結果。由於 glob 模組可以遍歷我們本地磁碟上的特定點的檔案列表,因此在使用檔案匹配模式時,我們必須滿足某些要求。該模組主要將遍歷僅遵循特定模式的檔案的磁碟檔案列表。
使用 glob() 遞迴搜尋檔案
此函式需要兩個引數:路徑名和遞迴標誌
- 路徑名− 相對或絕對(包括檔名和完整路徑)(帶有 Unix shell 樣式萬用字元)。透過向 glob() 方法提供絕對或相對路徑,我們可以執行檔案搜尋。具有完整目錄結構的路徑名稱為絕對路徑。相對路徑是包含目錄名稱和一個或多個萬用字元的路徑名。
- 遞迴− 如果設定為 True,則將執行遞迴檔案搜尋。它遞迴搜尋當前目錄的子目錄中的所有檔案。遞迴標誌的預設設定為 False。這意味著它將只查詢搜尋路徑中列出的資料夾。
它遞迴搜尋當前目錄的子目錄中的所有檔案。遞迴標誌的預設設定為 False。這意味著它將只查詢搜尋路徑中列出的資料夾。
語法
glob.glob(pathname, *, recursive=False)
示例
以下是如何使用 glob.glob() 方法使用絕對路徑列出目錄內容的示例
import glob # relative path for searching all the python files contents = glob.glob("D:\Work TP\*.py",recursive=True) print(contents)
輸出
以下是上述程式碼的輸出 -
['D:\Work TP\moving files.py', 'D:\Work TP\mysql_access.py', 'D:\Work TP\stored procedure python-sql.py', 'D:\Work TP\trial.py']
使用 iglob() 迴圈遍歷檔案
iglob() 和 glob() 之間的唯一區別在於,前者提供了一個符合模式的檔名迭代器。該方法生成一個迭代器物件,我們可以遍歷該物件以獲取各個檔案的名稱。
語法
glob.iglob(pathname,*,recursive=False)
在不實際將所有專案儲存在一起的情況下,返回一個生成與 glob() 相同值的迭代器。
當被呼叫時,iglob() 生成一個可呼叫物件,該物件將結果載入到記憶體中。
示例
以下是如何使用 glob.iglob() 方法列出目錄內容的示例 -
# importing the module import glob # providing the path glob.iglob('D:\Work TP/*.py') # iterating over the files in that path of directory for items in glob.iglob('D:\Work TP/*.py'): print(items)
輸出
以下是上述程式碼的輸出 -
D:\Work TP\moving files.py D:\Work TP\mysql_access.py D:\Work TP\stored procedure python-sql.py D:\Work TP\trial.py
Pathlib 模組
從 Python 3.4 開始,我們可以使用 pathlib 模組,它為大多數 OS 函式提供了包裝器。
- import pathlib− 對於許多作業系統,Pathlib 模組提供類和方法來管理檔案系統路徑並檢索與檔案相關的資料。
- 接下來,使用 pathlib.Path('path') 構造目錄的路徑。
- 接下來,使用 iterdir() 遍歷目錄中的每個條目。
- 最後,使用 path.isfile() 函式確定當前元素是否為檔案。
示例
以下是如何使用 pathlib 模組列出目錄內容的示例 -
# importing the module import pathlib # path of the directory dir_path = r'D:\Work TP' # storing the file names res = [] # constructing the path object d = pathlib.Path(dir_path) # iterating the directory for items in d.iterdir(): # checking if it's a file if items.is_file(): res.append(items) print(res)
輸出
以下是上述程式碼的輸出 -
[WindowsPath('D:/Work TP/moving files.py'), WindowsPath('D:/Work TP/mysql_access.py'), WindowsPath('D:/Work TP/stored procedure python-sql.py'), WindowsPath('D:/Work TP/trial.py')]