import os, re
while True:
keyword = input("请输入你要删除的字符串:")
if len(keyword)==0 or keyword.isspace():
print("字符串不能为空!")
else:
break
suffix = input("需要筛选的文件名后缀(Enter代表所有):")
fileNames = os.listdir() #获取当前目录下的所有文件
for file in fileNames:
check = os.path.join(os.path.abspath('.'),file)
if os.path.isfile(check):
if len(suffix)==0 or suffix.isspace():
if keyword in file:
print(file," -> ",file.replace(keyword,''))
os.rename(file,file.replace(keyword,''))
else:
#用正则表达式匹配后缀名
if re.match('.+?\.'+suffix+'$',file) != None and keyword in file:
print(file," -> ",file.replace(keyword,''))
os.rename(file,file.replace(keyword,''))
这段代码实现了一个功能,允许用户输入要删除的字符串和文件名后缀,然后遍历当前目录下所有文件,若文件名包含指定字符串且(没有指定后缀或文件名匹配后缀),则进行字符串替换并重命名文件。
301

被折叠的 条评论
为什么被折叠?



