VisualExstasy
VisualExstasy

Reputation: 85

Deleting the same filename in various subdirectories

Is there a way for python to go into the subdirectory and the second subdirectory of a folder and delete a certain file? I have 1 directory and in it 20 other subdirectory and each of those have their own subdirectories with a certain file I want deleted. I know I can hardcode the path of each one but is there an easier way?

import os, glob
for filename in glob.glob("C:\sshconnect.py"):
    os.remove(filename) 

EDIT: I want it so lets say I have "C:\Stackoverflow\sshconnect.py" &"C:\Testing\Test1\sshconnect.py" & "C:\Test2\sshconnect.py", it should go through all those and delete sshconnect.py in all folders.

Upvotes: 1

Views: 54

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140286

You were almost there: glob returns a list of the expanded filepaths. Just iterate on them and remove the files.

Since you have 2 levels of files, you could do this:

import os, glob
for filename in glob.glob(r"C:\*\sshconnect.py")+glob.glob(r"C:\*\*\sshconnect.py"):
    try:
        os.remove(filename) 
    except FileNotFoundError as e:
        print(str(e))

(note the exception handling in case a file is protected: script continues)

or this if you want any depth:

for root,dirs,files in os.walk(r"C:\\"):
   for f in files:
       if f=="sshconnect.py":
          try:
             os.remove(os.path.join(root,f))
          except FileNotFoundError as e:
             print(str(e))

For legacy versions of python like 2.5, write except FileNotFoundError, e:

Upvotes: 2

Related Questions