最近又开始搞科研了,研究一些稀奇古怪的东西,今天分享的是一个文件批量命名的方式。(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))
大功告成!!!!!!!