[英]Python save images from URL to different folders with custom name and structure
I have a.csv file with image urls, and I need to save each image in a different folder like the tree in URL.我有一个带有图像网址的.csv 文件,我需要将每个图像保存在不同的文件夹中,例如 URL 中的树。 For example, here 3 URL
比如这里3 URL
https://citynews.stgy.ovh/~shared/uploads/files/794/794964898449/62325865102181/logo_1.pic
https://citynews.stgy.ovh/~shared/uploads/files/420/42030573107817/62325865102181/logo_1.pic
https://citynews.stgy.ovh/~shared/uploads/files/218/21897603939378/62325865102181/logo_1.pic
I need that every image is saved in a different folder tree named as path url, like this:我需要将每个图像保存在名为路径 url 的不同文件夹树中,如下所示:
This should do it:这应该这样做:
import os
import urllib.request as urllib2
BASE_DIR = "C:\\workspace"
urls = ["https://citynews.stgy.ovh/~shared/uploads/files/794/794964898449/62325865102181/logo_1.pic",
"https://citynews.stgy.ovh/~shared/uploads/files/420/42030573107817/62325865102181/logo_1.pic",
"https://citynews.stgy.ovh/~shared/uploads/files/218/21897603939378/62325865102181/logo_1.pic"
]
for url in urls:
split_path = url.split("~shared/")[1]
img_name = os.path.basename(split_path)
dir_name = os.path.dirname(split_path)
path = os.path.join(BASE_DIR, dir_name)
print(path)
os.makedirs(path, exist_ok = True)
urllib2.urlretrieve(url, os.path.join(path, img_name))
print("done")
Also, read this link: python-os-makedirs另外,请阅读此链接: python-os-makedirs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.