迭代指定目錄中的檔案
當處理特定目錄中的檔案時,有必要有效地迭代它們。以下是在 Python 中完成此任務的逐步指南:
使用 os 模組:
os 模組提供了一組全面的函數用於與作業系統。要迭代特定目錄中的文件,請使用以下程式碼:
import os # Replace '/path/to/dir/' with your actual directory path directory = '/path/to/dir/' # Loop through the files in the directory for filename in os.listdir(directory): # Check if the file has the desired extension if filename.endswith('.asm'): # Perform desired actions on the file pass
使用pathlib 模組:
pathlib 模組提供了一種更物件導向的方法用於文件處理。以下是如何使用 pathlib 迭代檔:
from pathlib import Path # Replace '/path/to/dir/' with your actual directory path directory = '/path/to/dir/' # Create a Path object for the directory path = Path(directory) # Iterate over the files in the directory for file in path.glob('**/*.asm'): # Perform desired actions on the file pass
以上是如何在Python中有效率地迭代特定目錄中的檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!