如何使用 Python 刪除交換檔案?


本文將教你如何使用 Python 遞迴刪除資料夾中所有具有特定副檔名的檔案。

當我們提供資料夾路徑和副檔名時,應用程式將刪除資料夾內所有具有指定副檔名的檔案。

示例 - 使用 file.endswith() 方法

刪除交換檔案的步驟如下:

  • 匯入 _os_ 模組並從中匯入 _listdir_。使用 _listdir_ 檢視特定資料夾中所有檔案的列表,並使用 _os_ 模組刪除檔案。
  • 包含所有檔案的資料夾的路徑稱為 folderpath。
  • 正在迴圈遍歷指定資料夾中的檔案。使用 _listdir_ 命令獲取特定資料夾中所有檔案的單個列表。
  • 使用 endswith 函式確定檔案是否以 .txt 副檔名結尾。此“if 條件”將確保我們正在刪除目標資料夾中的所有 .txt 檔案。
  • 如果檔名以 .txt 結尾,我們使用 os.remove() 函式刪除該檔案。此函式的引數是檔案路徑。我們正在刪除的檔案的完整路徑是 folderpath + filename。

以下是使用 **file.endswith()** 方法刪除交換檔案的示例:

# importing the modules import os from os import listdir # Providing the path path = 'C:\Users\Lenovo\Downloads\Work TP\' # iterating the files in folder for file in listdir(path): # checking whether the files ends with .py extension if file.endswith('.txt'): os.remove(path + file) print("File Remoived Successfully...")

輸出

執行上述程式碼後,我們可以看到資料夾中副檔名為 **.txt** 的檔案被刪除。顯示以下訊息:

File Remoived Successfully...

示例 - 使用 os.path.join 命令

為了確保命令理解您在此操作中查詢的資料夾,必須將檔名新增到檔案路徑中。

使用 Python 中的 os.path.join 命令,您可以準確且可移植地完成此任務。

**.swp** 是交換檔案的副檔名。遞迴刪除資料夾中所有交換檔案的簡單方法是使用字串函式 endswith 來匹配檔名和副檔名(.swp)。

以下是使用 os.path.join 命令刪除交換檔案的示例:

import os, os.path mypath = "C:\Users\Lenovo\Downloads\Work TP" for root, dirs, files in os.walk(mypath): for file in filter(lambda x: x.endswith('.txt'), files): os.remove(os.path.join(root, file)) print("File Remoived Successfully...")

輸出

作為上述程式碼的輸出,我們可以看到資料夾中副檔名為 .txt 的檔案被刪除。顯示以下訊息:

File Removed Successfully...
目錄,“my_folder”並刪除所有以 .swp 結尾的檔案。

更新於: 2022年8月17日

630 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告