簡體   English   中英

根據命名約定,使用Python刪除Windows中的文件

[英]Deleting files in Windows, according to a naming convention, using Python

我正在嘗試用Python編寫程序。 我希望能夠將此程序指向一個目錄,比方說C:\\User\\Desktop\\Folder 此文件夾包含兩種類型的HTML文件,其中一個文件名以...abc.html ,另一個以...def.html 我想以遞歸方式刪除C:\\User\\Desktop\\Folder所有文件夾和子文件C:\\User\\Desktop\\Folder ,以def.html 這樣做的最佳方式是什么?

我試過這樣做:

import os
def deleteFiles(path):
 files = os.listdir(path)
 for f in files:
  if not os.path.isdir(f) and "DEF.html" in f:
   os.remove(f)
  if os.path.isdir(f):
   deleteFiles(path + "/" + f)

deleteFiles("C:\Users\ADMIN\Desktop\TestCode")

但是,在PyCharm中運行它,我收到一個錯誤:

WindowsError: [Error 2] The system cannot find the file specified: 'testDEF.html'

我在這做錯了什么?

您需要將os.remove(f)更改為os.remove(os.path.join(path, f))

順便說一句,建議硬編碼路徑不是推薦的最佳實踐。 即你應該這樣創建你的路徑:

deleteFiles(os.path.join(path, f))
deleteFiles(os.path.join('C:', 'Users', 'ADMIN', 'Desktop', 'TestCode')

這樣你的分隔符('/'或'\\')就會自動適合你的平台。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM