Coding-重命名文件夹下图像(数字方式and指定开头方式)

按顺序重命名pic文件夹下的图像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import os
import shutil

def rename_files_in_folder(folder_path, extension=".jpg"):#可改成别的后缀
"""
重命名指定文件夹内的所有指定扩展名的文件,按照序列1, 2, 3...进行命名。
"""
# 获取文件夹内所有指定扩展名的文件列表
files = [f for f in os.listdir(folder_path) if f.endswith(extension)]
files.sort() # 确保按文件名排序,如果需要的话

# 在同一文件夹内重命名文件
for index, filename in enumerate(files, start=1):
old_path = os.path.join(folder_path, filename)
new_filename = f"{index}{extension}"
new_path = os.path.join(folder_path, new_filename)

# 重命名文件
shutil.move(old_path, new_path)
print(f"Renamed '{filename}' to '{new_filename}'")

# 指定文件夹路径
pic_folder = "pic"

# 调用函数
rename_files_in_folder(pic_folder)

以指定开头命名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import os

def rename_files_in_directory(directory, prefix="self_"):
"""
Renames all files in the given directory to have the specified prefix.

:param directory: The directory path containing the files to rename.
:param prefix: The prefix to add before the original filename.
"""
try:
# Walk through all the files in the directory
for filename in os.listdir(directory):
# Construct the full file path
file_path = os.path.join(directory, filename)

# Check if it's a file (not a directory or link)
if os.path.isfile(file_path):
# Construct new filename with prefix
new_filename = prefix + filename

# Construct the new file path
new_file_path = os.path.join(directory, new_filename)

# Rename the file
os.rename(file_path, new_file_path)

print(f"Renamed '{filename}' to '{new_filename}'")
except Exception as e:
print(f"An error occurred: {e}")

# Example usage:
directory_to_rename = "labels"
rename_files_in_directory(directory_to_rename)