python - 根据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')
解决方案
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
推荐阅读
- service-worker - 当资源未缓存且脱机时,Workbox 重定向客户端页面
- visual-studio-code - How to setup VS Code to debug both blazor app and api project
- java - LoginServlet connecting to Customer Object
- javascript - How do i use the direction property for a bootstrap 4 carousel?
- swift - How do you group arrays with differing values in Swift?
- python - confluent-kafka-python consumer unable to read messages
- sql - 雪花 SQL 代码仅显示具有重复 ID 的项目的第二条记录
- c++ - Why is this variable considered an lvalue?
- c++ - c++,termios,非规范,阻塞,检测消息结束
- java - setOnClickListener - 如何检测是否在视图之外单击