0

I am dealing with a file directory in python, where I want to delete files containing a specific string, ultimately using os.remove(), but I just cannot get it to work. I will elaborate further here by showing the code I am using:

directory = 'source_folder'
for color in colors:
 for size in sizes:
 for speed in speeds:
 
 source = os.listdir(os.path.join(directory, color, size, speed))
 
 for file in source:
 if "p_1" in file:
 print(file)

And this prints out all the files in the directory that contain the string excerpt "p_1" in the file name, which is what I would expect. Each "for" nesting represents navigating to another folder level in my directory hierarchy.

What I want to do is delete every file that does NOT contain "p_1" in the file name. And so I tried:

directory = 'source_folder'
for color in colors:
 for size in sizes:
 for speed in speeds:
 
 source = os.listdir(os.path.join(directory, color, size, speed))
 
 for file in source:
 if "p_1" not in file:
 os.remove(file)

but this returns:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Name_of_one_of_the_files_I_want_to_delete'

I don't see where my logic is wrong here, since I can print the files I want to delete, but for some reason I can't delete them. How can I fix my code to delete those files that contain the string excerpt "p_1" in the file name?

asked Oct 21, 2021 at 3:10
1
  • 1
    That print(file) is your best clue. It printed a file name, not the filename plus directory. You need to add the directory to that name. Commented Oct 21, 2021 at 3:22

1 Answer 1

2

You need to specify the directory for the file to be removed. I would create a variable to hold the string of the file path like this:

directory = 'source_folder'
for color in colors:
 for size in sizes:
 for speed in speeds:
 
 some_path = os.path.join(directory, color, size, speed)
 source = os.listdir(some_path)
 
 for file in source:
 if "p_1" not in file:
 os.remove("/".join(some_path,file))
answered Oct 21, 2021 at 3:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.