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

问题描述 投票:0回答:2

我有一些带有方括号的文本,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(']', ''))
python brackets
2个回答
0
投票

如果您不想对特定的文件扩展名强制执行此操作,则只需删除条件:

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\\"

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

0
投票

使用代替* .txt

files_to_rename = fnmatch.filter(os.listdir(file_path), '*.*')
© www.soinside.com 2019 - 2024. All rights reserved.