跨不同文件扩展名使用Python删除文件名中的方括号
我有一些文本、pdf和doc文件,它们有括号,我希望在文件名中删除它们 例如[Alpha].txt-->Alpha.txt 下面的代码可以工作,但它只在一个文件扩展名上工作。有没有办法在同一代码中包含.pdf和.doc文件跨不同文件扩展名使用Python删除文件名中的方括号,python,brackets,Python,Brackets,我有一些文本、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\\Sou
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')
也许你可以试着使用。这是否回答了您的问题?