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()
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With