How to create a folder and save images in Python?
To create a folder and store images in Python, you can use the os module to handle file and folder operations, along with the PIL (Python Imaging Library) library to open and save images.
Here is an example code that demonstrates how to create a folder named “images” and store image files in it:
import os
from PIL import Image
# 创建文件夹
folder_name = "images"
os.makedirs(folder_name, exist_ok=True)
# 图像路径
image_path = "path_to_image.jpg"
# 打开图像
image = Image.open(image_path)
# 保存图像到文件夹
image.save(os.path.join(folder_name, "image.jpg"))
# 关闭图像
image.close()
The os.makedirs function is used to create a folder in the above code. Setting exist_ok=True as a parameter ensures that no error will be raised if the folder already exists.
Next, open the image file using the Image.open function, save the image to a specified folder using the image.save function, and finally, close the image using image.close.
Please make sure to replace “image_path” with the actual file path of the image and modify the folder name and the file name for saving the image as needed.