Search code examples
pythonnested-loopsdirectory

Removing files from a list of folders


I have a list of folders inside my directory and within each folder I am trying to remove all the files that start with the letter 'P'.

How can I get my second for loop to iterate over all the files from within each folder? At the moment it is just iterating over the name of each folder instead of the files from within.

folder_list_path = 'C:\Users\jack\Desktop\cleanUp'
for folder in os.listdir(folder_list_path):
    print folder
    for filename in folder:
        os.chdir(folder)
        if filename.startswith("P"):
            os.unlink(filename)
            print 'Removing file that starts with P...'

Solution

  • In your program folder is a relative path. try this modified version of your program :

    import os
    folder_list_path = 'C:\Users\jack\Desktop\cleanUp'
    for folder in os.listdir(folder_list_path):
        print folder
        subdir=os.path.join(folder_list_path,folder)
        for file in os.listdir(subdir):
            path=os.path.join(subdir,file)
            if os.path.isfile(path) and file.startswith("P"):
                print 'Removing file that starts with P...'
                os.unlink(path)