python在jpg文件命名后面添加数字

import os

i = 0
dirPath = '路径'

for (path,dirs,files) in os.walk(dirPath):
	
	for fileName in files:
		if fileName.endswith('.jpg'):	#使用endswith函数判断是否为jpg后缀


			number = str(i+1)
			fileNumber = number.zfill(6) #使用zfill函数将位数扩大到6位
			#print(fileNumber) 
			i = i + 1
			newName =  'city' + fileNumber + '.jpg'   #改名的命名规则
			#newName = fileName.replace('GXWZ201901','') #使用replace('要替换的字符串','替换后的字符串')替换字符串

			os.rename(path+fileName, path+newName) #使用函数rename(改名前的路径,改名后的路径)
		
			print(newName)
		else:
			print('no')

  工作中经常将jpg文件的后面添加数字,而且在文件夹中经常遇到非jpg文件,所以脚本先将文件夹里文件遍历一次,后判断文件是否是jpg文件,再添加数字,最后才改名。

posted @ 2019-03-12 10:20  StandardGX  阅读(396)  评论(0)    收藏  举报