如何使用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日

626 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告