python重命名

# -*- coding: utf-8 -*-
import os
path = "H:\\test_datasets\\zxwdata"
filelist = os.listdir(path) #该文件夹下所有的文件(包括文件夹)
count=1
for file in filelist:print(file)
for file in filelist:   #遍历所有文件Olddir=os.path.join(path,file)   #原来的文件路径if os.path.isdir(Olddir):   #如果是文件夹则跳过continuefilename=os.path.splitext(file)[0]   #文件名filetype=os.path.splitext(file)[1]   #文件扩展名filename="zxw"Newdir=os.path.join(path,filename+str(count).zfill(4)+filetype)  #用字符串函数zfill 以0补全所需位数os.rename(Olddir,Newdir)#重命名count+=1

# -*-coding: utf-8 -*-import osclass BatchRename():def __init__(self):self.path = 'H:\\test_datasets\\zxwdata'def rename(self):filelist = os.listdir(self.path)total_num = len(filelist)i = 1for item in filelist:if item.endswith('.jpg'):src = os.path.join(os.path.abspath(self.path), item)dst = os.path.join(os.path.abspath(self.path), str(i) + '.jpg')try:os.rename(src, dst)print ('converting %s to %s ...' % (src, dst))i = i + 1except:continueprint ('total %d to rename & converted %d jpgs' % (total_num, i))if __name__ == '__main__':demo = BatchRename()demo.rename()

# coding:utf8
import os
# 目标文件夹图像路径
path='H:/zxwTest/test'
#返回指定的文件夹包含的文件或文件夹的名字的列表
filelist=os.listdir(path)
j=0
for i in filelist:# 判断该路径下的文件是否为图片if i.endswith('.jpeg'):# 打开图片,将多个路径组合后返回src=os.path.join(os.path.abspath(path),i)# 图像路径 + a + 右对齐且字符串长度为3 +.jpgdst=os.path.join(os.path.abspath(path),'a'+format(str(j),'0>3s')+'.jpg')# 重命名函数os.rename(src,dst)j+=1

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部