python 文件批量命名按照顺序

最近又开始搞科研了,研究一些稀奇古怪的东西,今天分享的是一个文件批量命名的方式。(PS:按照文件的原始顺序),网上目前好多都不是按顺序命名,搞的很烦

话不多说上代码

1、首先你得保证文件名的格式相同。如下所示

 这里file后面的位数得保持一致,如果不一致(比如file_1.tif,file_10.tif,file_100tif,这种就是格式不一致,如果不调整会导致后面的批量命名无法按顺序),调整代码如下

directory_path = "I:\\LSTM(1)\\SA-ConvLSTM-Pytorch-main\\data\\filed data\\stea_re"

# # Get a list of all the files in the directory
 files = os.listdir(directory_path)

# # Loop through each file and rename it
for file in files:
   # Split the file name and extension
    file_name, file_ext = os.path.splitext(file)

     # Check if the file name starts with "FILE_" and ends with a number
     if file_name.startswith("FILE_") and file_name[5:].isdigit():
         # Get the number from the file name
         num = int(file_name[5:])

         # Construct the new file name with three digits
         new_file_name = f"FILE_{num:03}{file_ext}"

         # Rename the file
         os.rename(os.path.join(directory_path, file), os.path.join(directory_path, new_file_name))

调整完,如上图所示

2、按顺序命名

import os
#
# # Get the directory path where the files are located
directory_path = "I:\\LSTM(1)\\SA-ConvLSTM-Pytorch-main\\data\\filed data\\stea_re200_pic"
#
# # Get a list of all the files in the directory
files = os.listdir(directory_path)

files.sort()

# Loop through each file and rename it
for i, file in enumerate(files):
    # Construct the new file name
    new_file_name = f"rot_re200_{(0.02*i)+90:.2f}_vort.tiff"

    # Rename the file
    os.rename(os.path.join(directory_path, file), os.path.join(directory_path, new_file_name))

大功告成!!!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰虺

万水千山总是情,给点打赏行不行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值