python批量修改文件夹下的图片名称(3种方法)

python批量修改文件夹下的图片名称
本人下载了逐日1KM LST数据,但是里面有部分文件夹下的数据命名和其他的数据命名不一致,所以需要批量命名。

添加自己的文件路径和修改自己要的图片名称,本方法是直接在原文件路径中修改图片名称,若不想覆盖之前的图片名,请先备份。

import os
import re
#coding=utf-8
"""批量修改文件夹的图片名"""

def ReFigName(dirPath):
      ####param dirPath: 文件夹路径
    # 对目录下的文件进行遍历
    for file in os.listdir(dirPath):
        print(file)
        # 判断是否是文件
        if os.path.isfile(os.path.join(dirPath, file)) == True:
           newfile = file[0:7] + "N" + ".tif"##在此处修改自己想要的图片名即可
           # 重命名
           os.rename(os.path.join(dirPath, file), os.path.join(dirPath, newfile))
    print("***修改成功***")

if __name__ == '__main__':

    dirPath = r"...\myt\myt2"###添加自己的文件路径即可
    ReFigName(dirPath)

在这里插入图片描述
效果如图,均加了一个字母N,可根据自己需要,自己修改代码。。。

方法2:用python的shutil的rename。

import os
import re
import shutil
#coding=utf-8
"""批量修改文件夹的图片名"""
def ReFileName(dirPath):
      ####param dirPath: 文件夹路径
    # 对目录下的文件进行遍历
    for file in os.listdir(dirPath):
        print(file)
        # 判断是否是文件
        if os.path.isfile(os.path.join(dirPath, file)) == True:
           newfile = file[0:7] + "N" + ".tif"
           # 重命名
           os.rename(os.path.join(dirPath, file), os.path.join(dirPath, newfile))
    print("***搞定了哈!!!***")

方法3:用python的shutil的copy函数,在复制的时候修改。这样不用担心覆盖原来的文件。

import os
import re
import shutil
#coding=utf-8
"""批量修改文件夹的图片名"""
def ReFileName(dirPath,outPath):
      ####param dirPath: 文件夹路径
    # 对目录下的文件进行遍历
    for file in os.listdir(dirPath):
        print(file)
        # 判断是否是文件
        if os.path.isfile(os.path.join(dirPath, file)) == True:
           newfile = file[0:7] + "N" + ".tif"
           # 重命名
           shutil.copy(os.path.join(dirPath, file),os.path.join(outPath, newfile))
    print("***搞定了哈!!!***")
  • 15
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值