You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu系统下使用Python将下载图片保存至指定目录的方法

How to Save Downloaded Images to a Specified Directory

No problem at all! To save your images to a target directory instead of the current working folder, you just need to include the full or relative path when defining the file name. Here's how to adjust both your code snippets, plus a tip to avoid common path issues:

1. For urllib.request.urlretrieve

Instead of just using name+".jpeg", prepend your target directory path. It's best to use os.path.join() to handle cross-platform path separators (like / vs \):

import urllib.request
import os

# Define your target directory (can be relative or absolute)
target_dir = "./my_images"  # Relative path from current directory
# Or use an absolute path like: "/Users/Meera/Documents/downloaded_images"

# Make sure the directory exists (create it if not)
os.makedirs(target_dir, exist_ok=True)

# Combine directory and file name
file_path = os.path.join(target_dir, f"{name}.jpeg")

# Download and save to the specified path
urllib.request.urlretrieve(url, file_path)

2. For requests.get

Same logic applies here—build the full file path with your target directory. Also, using a with statement is cleaner as it auto-closes the file:

import requests
import os

target_dir = "./my_images"
os.makedirs(target_dir, exist_ok=True)

file_path = os.path.join(target_dir, f"{name}.jpeg")

response = requests.get(url)
with open(file_path, "wb") as file:
    file.write(response.content)

Key Notes:

  • Relative vs Absolute Paths: A relative path (like ./my_images) starts from your current working directory. An absolute path (like C:\Users\Meera\Pictures on Windows or /home/meera/Pictures on Linux) points directly to the folder regardless of where your script runs.
  • os.makedirs: Adding exist_ok=True means the code won't throw an error if the directory already exists—perfect for repeated runs.
  • with Statement: This ensures the file is closed properly even if an error occurs, so you don't have to remember to call file.close() manually.

内容的提问来源于stack exchange,提问作者Meera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:43:13