我想要一个程序,它将帮助清理一堆文件的标题和结构,以便它们以适合我的媒体中心程序的格式。我编写了一个程序来清理我想要的父文件夹的名称"名称(年份)"。我在处理子文件的清理方面遇到了麻烦。这是我的基本伪代码:
Find all folders in given directory
Open each folder and copy or move files in child folders to main folder
Sort files by size
Rename the largest file the same name as the parent directory
Search for .srt files
if no .srt files delete all but largest file
if one .srt file found rename it same name as parent directory + .eng.srt
if multiple .srt files found search for "english" or "eng"
if one matching file found rename it same name as parent directory + .eng.srt
if multiple english or eng files found pick one without "SDH" and rename as above
Delete all files except renamed largest file and renamed .srt if found
我使用os.rename()重命名父目录,但管理子文件让我很困惑。 os.walk似乎是推荐的,但它根本不直观。如果存在这样的事情,我如何将目录作为对象进行管理?
答案 0 :(得分:0)
假设,重命名文件等于标记它以保留它(你的伪代码需要稍微修改一下):
from os import listdir, remove
from os.path import isfile, join
mainpath = "/tmp/"
renamed_files = []
每次重命名文件时,请将其添加到“待保留列表”中:
renamed_files.append(fname)
最后:
onlyfiles = [f for f in listdir(mainpath) if isfile(join(mainpath, f))]
for fname in onlyfiles:
if mainpath+fname not in renamed_files:
remove(mainpath+fname) # os.remove()