如何用Python擦除文件中的某些名称

时间:2018-02-21 17:00:27

标签: python operating-system rename

我正在尝试删除下载包含无用信息的奇怪名称的子文件夹的某些名称(在这种情况下,这些是电影文件,所以像720p,BluRay等。)

到目前为止,我的代码是:

os.chdir(r"E:\Users\Lucas\HD externo\Filmes_séries_documentários\Diretores")

lista = ["1080p","720p", "BDrip", "BRRip", "Xvid", "XViD","XviD", "ETRG", "Woody Allen", "DVDRip", "avi", "x264", "AC3-JYK", "BluRay", "DC", ".....anoXmous", "EXTENDED", "pt", "BR"]

for i in range(len(os.listdir())):
    for b in os.listdir():
        os.chdir(r"E:\Users\Lucas\HD externo\Filmes_séries_documentários\Diretores\\" + os.listdir()[i])
        for c in range(len(os.listdir())):
             for item in lista:
                 if item in os.listdir()[i]:
                     a = os.listdir()[i].replace(item, "")
                     os.rename(os.listdir()[i], a)

1 个答案:

答案 0 :(得分:0)

在浏览目录结构时使用os.walk是一个好主意。

如果您要删除该文件,请使用os.remove(filename)

import os

dir = r"C:\Windows\Path\"
lista = ['all','of','the','things']
for root, dirs, files in os.walk(dir):
    for file in files:
        for part in lista:
            if part in file:
                os.remove(os.path.join(root, file))