简体   繁体   中英

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

I am trying to write a program in Python. I want to be able to point this program to a directory, let's say C:\\User\\Desktop\\Folder . This Folder contains two types of HTML file, for one the filename ends in ...abc.html and the other it ends in ...def.html . I want to recursively delete, within all folders and sub-folders of C:\\User\\Desktop\\Folder , which end in def.html . What is the best way of doing this ?

I have tried to do it like so :

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")

Running this in PyCharm, however, I get an error :

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

What have I done wrong here ?

You need to change os.remove(f) to os.remove(os.path.join(path, f))

Btw, it is not a recommended best practice to create hard coded path. Ie you should create your path this way:

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

so that your separators ('/' or '\\') will fit your platform automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM