Search code examples
pythonsubdirectory

For folder in dir, enter it and delete files if condition is met


My dir looks something like this:

dir
|_folder1
  |_file1.py
  |_file2.png
|_folder2
  |_file1.py
  |_file2.png
|_etc..

I want to enter each folder and delete all files that don't have .py in their name, only part of the problem I don't know how to solve its how to know if the file is a folder and to enter it if is.

I tried with listdir() and asked for the type of each element in that list, but all were string, probably because it's just a list of names.


Solution

  • You should spend time to make this function more efficient. However, it will do what you want.

    import os
    
    def deleteNonPyFiles(parent_dir):
        no_delete_kw = '.py'
        for (dirpath, dirnames, filenames) in os.walk(parent_dir):
            for file in filenames:
                if no_delete_kw not in file:
                    os.remove(f'{dirpath}/{file}')
       
    deleteNonPyFiles('C:/User/mydirpath')