#-*- coding: UTF-8 -*-#Windows python 3.9.0 64bit
# Linux 好像不支持按照文件创建时间重命名
importosimporttime#####################################################################################################################################################
defgenerateNewName(timeStamp, format):
locTime=time.localtime(timeStamp)returntime.strftime(format, locTime)defrenameFileByModifyTime(dir, format):
longNewName= ''shortNewName= ''
for root, dirs, files inos.walk(dir):for name infiles:
baseName, ext=os.path.splitext(name)
longName=os.path.join(root, name)
modifyTimeStamp=os.path.getmtime(longName)
shortNewName=generateNewName(modifyTimeStamp, format)
longNewName= os.path.join(root, shortNewName +ext)
count= 1
whileos.path.exists(longNewName):
longNewName= os.path.join(root, shortNewName + '_' + str(count) +ext)
count+= 1os.rename(longName, longNewName)print('{} --> {}'.format(os.path.basename(longName), os.path.basename(longNewName)))defrenameFileByCreateTime(dir, format):
longNewName= ''shortNewName= ''
for root, dirs, files inos.walk(dir):for name infiles:
baseName, ext=os.path.splitext(name)
longName=os.path.join(root, name)
modifyTimeStamp=os.path.getctime(longName)
shortNewName=generateNewName(modifyTimeStamp, format)
longNewName= os.path.join(root, shortNewName +ext)
count= 1
whileos.path.exists(longNewName):
longNewName= os.path.join(root, shortNewName + '_' + str(count) +ext)
count+= 1os.rename(longName, longNewName)print('{} --> {}'.format(os.path.basename(longName), os.path.basename(longNewName)))#####################################################################################################################################################
if '__main__' == __name__:
dir= input('Please input directory path:')
format= input(r'Please input new file name format: (input 1 to use default format: IMG_%Y%m%d_%H%M%S, e.g. IMG_20102029_202550):')
model= input('Rename file by modify time or create time (1: modiry time, 2: create time):')print()if '1' ==format:
format= r'IMG_%Y%m%d_%H%M%S'
if '1' ==model:
renameFileByModifyTime(dir, format)elif '2' ==model:
renameFileByCreateTime(dir, format)else:print('input error')print()print('Done!')
input('Press any key to exit!')