首页 > 解决方案 > 根据Python中的列表重命名文件夹中的图像

问题描述

我有一个文件夹,其中包含从 1.jpg 到 1000.jpg 排序的大约 1000 张图像,我想用我随身携带的列表“x”重命名这些名称。

x = ["hello", "rat", ...]

这是我的列表,所以我想将图像的名称从 1.jpg 更改为 hello.jpg 等等。我该怎么做呢?

我想读取文件然后使用 os.rename(),但我不知道该怎么做

with open(x) as list1:
newnames = list1.read().split(',\n')

标签: python

解决方案


import os
my_list_of_new_names = ["hello", "rat", "etc..."]
my_dir = "C:\path_to_my_images\my_directory_of_images"
for filename in os.listdir(my_dir):
    filename = filename.split('.')
    try:
        new_name, ext = filename
        os.rename(filename, my_list[int(new_name)-1] + ext)
    except:
        #your list may not be the correct size
        pass

推荐阅读