python存储图片到D盘指定目录
时间: 2024-10-24 15:10:09 浏览: 35
在Python中,我们可以使用内置的`os`和`PIL`(Python Imaging Library,现在通常称为Pillow)库来将图片存储到D盘的特定目录。首先,确保已安装了这两个库,如果没有安装,可以通过pip进行安装:
```bash
pip install pillow
```
下面是一个简单的例子,展示了如何将一张图片保存到D盘的指定路径:
```python
import os
from PIL import Image
# 指定图片文件和目标目录
image_path = "path_to_your_image.jpg" # 替换为你图片的实际路径
target_directory = "D:/your_folder/" # D盘下的指定文件夹
# 确保目标目录存在,如果不存在则创建
if not os.path.exists(target_directory):
os.makedirs(target_directory)
# 图片文件名,这里直接使用原文件名
new_image_name = os.path.basename(image_path)
new_image_path = os.path.join(target_directory, new_image_name)
# 打开图片并保存到新的位置
with open(new_image_path, "wb") as img_file:
with Image.open(image_path) as im:
im.save(img_file)
print(f"图片已保存到 {new_image_path}")
```
请确保替换`image_path`为你实际要保存的图片路径,并将`D:/your_folder/`替换成你想要的D盘目标文件夹。
阅读全文
相关推荐


















