python批量修改png后缀为jpg
时间: 2024-12-14 08:14:21 浏览: 15
python批量修改图片后缀的方法(png到jpg)
在Python中,你可以使用`os`模块配合图像处理库如`PIL`(Python Imaging Library)来批量修改文件后缀名。以下是一个简单的步骤示例:
```python
import os
from PIL import Image
# 确定图片所在的目录
directory = '/path/to/your/images'
# 遍历指定目录下的所有png文件
for filename in os.listdir(directory):
if filename.endswith('.png'): # 检查是否为png文件
old_path = os.path.join(directory, filename) # 获取旧路径
new_filename = filename.replace('.png', '.jpg') # 修改后缀名为.jpg
new_path = os.path.join(directory, new_filename) # 获取新路径
try:
with Image.open(old_path) as img:
img.save(new_path) # 将PNG文件转换并保存为JPG
print(f"Converted {old_path} to {new_path}")
except Exception as e:
print(f"Error processing {old_path}: {e}")
阅读全文