根据命名约定,使用 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 的所有文件夹和子文件夹中递归删除以 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')

这样您的分隔符(“/”或“\”)将自动适合您的平台。