栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 批量修改图片文件名,实现00001开头

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 批量修改图片文件名,实现00001开头

代码如下:

import os
import re
import sys
###---------------------------如果原始文件名为纯数字,直接用这一部分就行,把这一部分注释取消
#path = '/home/xzn/桌面/darknet/VOCdevkit/VOC2007/JPEGImages'  #图片路径
#for file in os.listdir(path):
 #   if os.path.isfile(os.path.join(path,file))==  True:
  #      fname,ext=os.path.splitext(file)
   #     on=os.path.join(path,file)
    #    nn=os.path.join(path,str(fname).zfill(6)+ext)   # 数字6是定义为6位数,可随意修改需要的
     #   os.rename(on,nn)
###---------------------------如果原始文件为纯数字,直接用这一部分就行


###-------------------如果原始文件名不为纯数字,用下面一部分,把上面部分注释
path = '/home/xzn/桌面/darknet/VOCdevkit/VOC2007/JPEGImages'
for i,file in enumerate(os.listdir(path)):
    if os.path.isfile(os.path.join(path,file))==  True:
        fname,ext=os.path.splitext(file)
        on=os.path.join(path,file)
        nn=os.path.join(path,str(i+1)+ext)
        os.rename(on,nn)
path = r"/home/xzn/桌面/darknet/VOCdevkit/VOC2007/JPEGImages"
filelist = os.listdir(path)
filetype = '.jpg'
for file in filelist:
    print(file)
for file in filelist:
    Olddir = os.path.join(path, file)
    print(Olddir)
    if os.path.isdir(Olddir):
        continue

    # os.path.splitext("path"):分离文件名与扩展名
    filename = os.path.splitext(file)[0]
    filetype = os.path.splitext(file)[1]

    # zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0
    Newdir = os.path.join(path, filename.zfill(6) + filetype)  # 数字6是定义为6位数,可随意修改需要的
    os.rename(Olddir, Newdir)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/657080.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号