Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to check folders within folders? [duplicate]

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()
like image 988
SchrodingersStat Avatar asked Jan 01 '23 23:01

SchrodingersStat


2 Answers

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

like image 196
chris Avatar answered Jan 09 '23 21:01

chris


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.

like image 34
Harpe Avatar answered Jan 09 '23 21:01

Harpe