python - 批量修改文件名

1,892 阅读1分钟
  1. 批量修改文件夹下面文件名 XXXX-第一集.avi
import os

# inputPath=input('请输入文件路径(结尾加上/):')
path = "E:\\files"

# 获取该目录下所有文件,存入列表中

if not os.path.exists(path):
    print("目录不存在!!")
    os._exit(1)

fileList = os.listdir(path)

# 遍历文件夹中所有文件
for fileName in fileList:
    # 设置旧文件名(就是路径+文件名) security-info-2019-03-23_0
    oldname = fileName  # os.sep添加系统分隔符
    # 设置新文件名 截取前面的 security-info-
    newname = oldname[9:]
    if 'security-' in oldname:
       os.rename(path + os.sep + oldname, path + os.sep + newname)  # 用os模块中的rename方法对文件改名
    print(oldname, '======>', newname)
print('-----------------------分界线------------------------')

2 更通用的 www.cnblogs.com/dugu2036/p/…