我在一个目录中有大约600个电影文件夹每个电影文件夹都有一个.srt和.txt文件示例:
- 电影库/
- movies_brary/movie_1
- movies_brary/movie_1/movie1_name.pm4
- movies_library/movie_1/movie1.srt
- movies_library/movie_1/movie1.txt
- movies_brary/move2
- movies_brary/movie_2/movie2_name.pm4
- movies_library/movie_2/movie2.start
- movies_library/movie_2/movie2.txt
- movies_brary/movie_1
所以我需要删除.srt和.txt,我写了这个代码,它的工作很好,但我有两个问题:
- 如果你在主电影库文件夹中有一个.mp4文件,它会出错并停止脚本
- .DS存储也会停止脚本
import os
SRT = input("enter file type: n ")
src = input("Enter folder path: n")
folders_in_src_path = os.listdir(src)
folders_path_list = []
for file in folders_in_src_path:
full_folder_path = os.path.join(src, file)
p = folders_path_list.append(full_folder_path)
folders_path_list.remove(src + '/.DS_Store')
for x in folders_path_list :
file_in_folder = os.listdir(x)
filtered_files=[file for file in file_in_folder if file.endswith(SRT) ]
for file in filtered_files:
path_to_filterd_files = os.path.join(x, file)
os.remove(path_to_filterd_files)
试试这个:
import os
file_type = input("Enter file type: ")
folder_path = input("Enter folder path: ")
filelist = []
for root, dirs, files in os.walk(folder_path):
for file in files:
#append the file name to the list
filelist.append(os.path.join(root,file))
#print all the file names
for name in filelist:
delete_file = str(name)
if delete_file.endswith(file_type):
os.remove(delete_file)
print("File deleted successfully.")
break
else:
print("No files found.")
使用pathlib和os 查找我的解决方案
from pathlib import Path
import os
src_folder = Path(input("insert path : n"))
file_type = input("file type as mp4 : n" )
# use glob for directores and rglob for directories and subdirectories
# [!.] to exclude hiddin files start with [ directory/.filename.filetype] cuz it generate an error while os.remove
files_list = list(src_folder.rglob(f"[!.]*.{file_type}"))
# using X to add every filterd file path included in list
# to be removed item by item using os.remove
for X in files_list:
os.remove(X)
更新感谢@tomerikoo
from pathlib import Path
src_folder = Path(input("insert path : n"))
file_type = input("file type as mp4 : n" )
files_list = src_folder.rglob(f"[!.]*.{file_type}")
for X in files_list:
X.unlink()