在不同的文件扩展名中使用 Python 删除文件名中的括号

Removing brackets in filenames using Python across different file extensions

我有一些带有括号的文本、pdf 和 doc 文件,我希望将它们从文件名中删除。

例如。 [Alpha].txt --> Alpha.txt

下面的代码有效,但它只适用于特定的一个文件扩展名。有没有办法在同一代码中包含 .pdf 和 .doc 文件?

import os, fnmatch

#Set directory of locataion; include double slash for each subfolder.
file_path = "C:\Users\Mr.Slowbro\Desktop\Source Files\"

#Set file extension accordingly
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.txt')

for file_name in files_to_rename:
    file_name_new = file_name.replace('[', '')    
    os.rename(file_path + file_name, file_path + file_name_new)
    os.rename(file_path + file_name_new, file_path + file_name_new.replace(']', ''))

使用 . 代替 *.txt

files_to_rename = fnmatch.filter(os.listdir(file_path), '*.*')

所有文件都非常简单。只需将 '*.txt 替换为 *.**.* 表示具有任何文件扩展名的任何文件名:

import os, fnmatch

#Set directory of locataion; include double slash for each subfolder.
file_path = "C:\Users\Mr.Slowbro\Desktop\Source Files\"

#Set file extension accordingly
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.*') #All files included

for file_name in files_to_rename:
    file_name_new = file_name.replace('[', '')    
    os.rename(file_path + file_name, file_path + file_name_new)
    os.rename(file_path + file_name_new, file_path + file_name_new.replace(']', ''))

对于特定的扩展,只需组合列表:

import os, fnmatch

#Set directory of locataion; include double slash for each subfolder.
file_path = "C:\Users\Mr.Slowbro\Desktop\Source Files\"

#Set file extension accordingly
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.txt') + fnmatch.filter(os.listdir(file_path), '*.pdf') + fnmatch.filter(os.listdir(file_path), '*.doc')