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 (likeC:\Users\Meera\Pictureson Windows or/home/meera/Pictureson Linux) points directly to the folder regardless of where your script runs. os.makedirs: Addingexist_ok=Truemeans the code won't throw an error if the directory already exists—perfect for repeated runs.withStatement: This ensures the file is closed properly even if an error occurs, so you don't have to remember to callfile.close()manually.
内容的提问来源于stack exchange,提问作者Meera
相关产品推荐
相关产品推荐

