您可以使用标准 os 模块重命名文件
import os
os.rename('YOU_CURRENT_IMAGE_NAME.jpg', 'NEW_NAME.jpg')
假设您有一个名为 my_pic.jpg 的图像,并且您想将其重命名为 ID=abc 和 labe=2,那么代码如下所示:
import os
def rename_image(existing_name, _id, label):
existing_name = 'my_pic.jpg'
extension = existing_name.split('.')[-1]
new_name = f'{_id}-{label}.{extension}'
os.rename(existing_name, new_name)
rename_image('my_pic.jpg', 'abc', 2)
# new name is: abc-2.jpg
[已编辑]
假设您有一个名为“images”的文件夹,所有图片都存储在此文件夹中,并且您有一个这样的 csv 文件:
old_name1.jpg,new_name_001.jpg
another_old_pic.svg,new_name_for_this.svg
在这种情况下,重命名所有文件的简单 sn-p 如下所示:
import os
import csv
IMG_FOLDER = 'images' # name of your image folder
CUR_PATH = os.getcwd() # current working directory
img_dir = os.path.join(CUR_PATH, IMG_FOLDER) # full path to images folder
with open('images.csv') as csv_file:
csv_data = csv.reader(csv_file)
images = os.listdir(img_dir) # a list of file names in images folder
for row in csv_data:
# we iterate over each row in csv and rename files
old_name, new_name = row
# we are just checking in case file exists in folder
if old_name in images:
# main part: renaming the file
os.rename(
os.path.join(CUR_PATH, IMG_FOLDER, old_name),
os.path.join(CUR_PATH, IMG_FOLDER, new_name)
)
else:
print(f"Image {old_name!r} not found, skipping...")
您可以调整重命名部分,并在新图像名称中添加任何您想要的内容(我猜是您想要包含某种标签吗?)。