I've been learning python for some time and I've come up with the idea to practice it a little. I created a script that removes files by their extension .html and .srt and also empty directories. It works good, but I've got a feeling that it could be improved. Can someone help me improve the code? Also I know it is not a good practice to use for-loop inside another for-loop. Files structure:
super secret folder
|___empty folder
|___folder1
|___file01.jpg
|___file02.srt
|___file03.html
|___folder2
|___file01.jpg
|___file02.srt
|___file03.html
|___folder3
|___file01.jpg
|___file02.srt
|___file03.html
import os
mypath = "C:\\Users\\user\\super secret folder"
def extract_ext(file_path):
split_tuple = os.path.splitext(file_path)
return split_tuple[0], split_tuple[1]
def abs_path(my_file_path, file_name):
return f"{my_file_path}\\{file_name}"
subfolders_list = os.listdir(mypath)
subfolders_paths = [os.path.join(mypath, path) for path in subfolders_list]
for folder_path in subfolders_paths:
files_list = os.listdir(folder_path)
if len(files_list) != 0:
for file_name in files_list:
file_abs_path = abs_path(folder_path, file_name)
_, file_extension = extract_ext(file_abs_path)
if file_extension == ".html" or file_extension == ".srt":
os.remove(file_abs_path)
else:
os.rmdir(folder_path)
pathlib.Path
overrides the division operator and adds OS specific separators:path1 / path2
="path1Content\path2Content"
on Windows and"path1Content/path2Content"
on POSIX \$\endgroup\$