5

First off, let me apologize if the title is unclear.

To simplify a task I do at work, I've started writing this script to automate the removal of files from a certain path.

My issue is that in its current state, this script does not check the contents of the folders within the folder provided by the path.

I'm not sure how to fix this, because from what I can tell, it should be checking those files?

import os


def depdelete(path):
    for f in os.listdir(path):
        if f.endswith('.exe'):
            os.remove(os.path.join(path, f))
            print('Dep Files have been deleted.')
        else:
            print('No Dep Files Present.')


def DepInput():
    print('Hello, Welcome to DepDelete!')
    print('What is the path?')
    path = input()
    depdelete(path)


DepInput()
SchrodingersStat
  • 291
  • 3
  • 19

4 Answers4

6

Try using os.walk to traverse the directory tree, like this:

def depdelete(path):
    for root, _, file_list in os.walk(path):
        print("In directory {}".format(root))
        for file_name in file_list:
            if file_name.endswith(".exe"):
                os.remove(os.path.join(root, file_name))
                print("Deleted {}".format(os.path.join(root, file_name)))

Here are the docs (there are some usage examples towards the bottom): https://docs.python.org/3/library/os.html#os.walk

chris
  • 1,915
  • 2
  • 13
  • 18
1

Currently, your code just loops over all files and folders in the provided folder and checks each one for its name. In order to also check the contents of folders within path, you have to make your code recursive.

You can use os.walk to go through the directory tree in path and then check its contents.

You'll find a more detailed answer with code examples at Recursive sub folder search and return files in a list python.

Harpe
  • 316
  • 1
  • 9
1

Take a look at os.walk()

This function will iterate through sub-directories for you. The loop will look like this.

for subdir, dirs, files in os.walk(path):
    for f in files:   
      if f.endswith('.exe'):
          fullFile = os.path.join(subdir, f)
          os.remove(fullFile)
          print (fullFile + " was deleted")
Bill S.
  • 96
  • 7
1

You're looking for os.walk(). In your case, it could work like so:

import os

def dep_delete(path):
    for path, dirs, files in os.walk(path):
       for f in files: 
           if f.endswith('.exe'):
               os.remove(os.path.join(path, f))
    print('Dep files have been deleted.')

def dep_input():
    print('Hello, Welcome to dep_delete!')
    print('What is the path?')
    path = input()
    dep_delete(path)


dep_input()

Also see: List directory tree structure in python?