Reputation: 103
I have a folder, which contains many subfolders, each containing some videos and .srt files. I want to loop over the main folder so that all the .srt files from all subfolders are deleted.
Here is something I tried-
import sys
import os
import glob
main_dir = '/Users/Movies/Test'
folders = os.listdir(main_dir)
for (dirname, dirs, files) in os.walk(main_dir):
for file in files:
if file.endswith('.srt'):
os.remove(file)
However, I get an error as follows-
FileNotFoundError: [Errno 2] No such file or directory: 'file1.srt'
Is there any way I can solve this? I am still a beginner so sorry I may have overlooked something obvious.
Upvotes: 2
Views: 2045
Reputation: 3621
You need to join the filename with the location.
import sys
import os
main_dir = '/Users/Movies/Test'
for (dirname, dirs, files) in os.walk(main_dir):
for file in files:
if file.endswith('.srt'):
source_file = os.path.join(dirname, file)
os.remove(source_file)
Upvotes: 4