Python 批量文件重命名脚本
用文件元数据中的 mtime 批量重命名当前目录中的文件
import os
import time
# 获取当前工作路径
cwd = os.getcwd()
# 迭代目录中的文件
for file in os.listdir(cwd):
filename = file.split('.')[0]
extname = file.split('.')[1]
info = os.stat(file)
timestamp =info.st_mtime
# 时间戳转成时间对象
localtime = time.localtime(timestamp)
newname = time.strftime("%Y-%m-%d_%H%M%S", localtime) + '.' + extname
try:
os.rename(file, newname)
print('文件 %s \n 已重命名为 \n %s' % (file, newname))
except (IOError, Exception) as e:
print('重命名时发生错误!')
print(e)
print('')
print('批量重命名任务完成!')
Member discussion