Home » Questions » Computers [ Ask a new question ]

Unable to delete files from folder using os.remove() in python -

Unable to delete files from folder using os.remove() in python -

"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?





python file directory operating-system












ShareShare a link to this question Copy linkCC BY-SA 4.0




Follow
Follow this question to receive notifications











asked 8 mins ago





LostinSpatialAnalysisLostinSpatialAnalysis

23566 bronze badges"

Asked by: Guest | Views: 116
Total answers/comments: 0