Python批量修改文件名(删除指定关键字)

因下载的视频文件大多数含有视频网站的url或者包含其他不要的字符串,用python自动修改。


目前缺点:

1,需要把.py放在目录内运行


代码如下:

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,''))


猜你喜欢

转载自blog.51cto.com/8540002/2409221
今日推荐