Reputation: 641
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?
Upvotes: 0
Views: 4420
Reputation: 36
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))
Upvotes: 2