[英]How to download/save images from a csv file using url into specific created folder on my local Windows Machine?
I am trying to download the images which are available as url in csv file into specific folders (named as Male, Female for classification) I created in my C:/Desktop/Images.我正在尝试将 csv 文件中的 url 可用的图像下载到我在 CZtop/Images 中创建的特定文件夹中(命名为男性,女性用于分类)。 But when I run the below code, nothing is getting downloaded and getting saved into the specific folders based on the category as present in my csv file.
但是当我运行下面的代码时,没有任何内容被下载并保存到基于我的 csv 文件中存在的类别的特定文件夹中。 The contents in my csv are as in below format.
我的 csv 中的内容如下所示。 It has several thousands of rows.
它有几千行。 I am trying to iterate and save the specific gender image to that particular folder created above
我正在尝试迭代并将特定性别图像保存到上面创建的特定文件夹中
Format:
Male profilename https://pbs.twimg.com/profile_images/414342229096808449/fYvzqXN7_normal.png
**Code:**
import urllib.request
import urllib.error
import sys
filename = "images"
with open("{0}.csv".format(filename), 'r') as csvfile:
i = 0
for line in csvfile:
splitted_line = line.split(',')
try:
if ((splitted_line[2] != "\n") and (splitted_line[2] != '') and (splitted_line[0] == male)):
fullfilename_1 = os.path.join('C:/Desktop/Images/Male', splitted_line[1])
urllib.request.urlretrieve(splitted_line[2], fullfilename_1 + ".png")
print ("Image saved for {0} in {1} ".format(splitted_line[1],'C:/Desktop/Images/Male'))
i += 1
except:
print ("No result for {0}".format(splitted_line[1]))
try:
if ((splitted_line[2] != "\n") and (splitted_line[2] != '') and (splitted_line[0] == female)):
fullfilename_1 = os.path.join('C:/Desktop/Images/Female', splitted_line[1])
urllib.request.urlretrieve(splitted_line[2], fullfilename_1 + ".png")
print ("Image saved for {0} in {1} ".format(splitted_line[1],'C:/Desktop/Images/Female'))
i += 1
except:
print ("No result for {0}".format(splitted_line[1]))
How would I be able to download/save to the specific folder as mentioned?我如何能够下载/保存到提到的特定文件夹? Is there any issue with my path not being properly mentioned?
我的路径没有被正确提及有什么问题吗? Any help would kindly be appreciated!
任何帮助将不胜感激!
First change "images.csv" to "images.txt", then run this code:首先将“images.csv”更改为“images.txt”,然后运行以下代码:
import urllib.request
data = open("images.txt")
lines = data.readlines()
for row in lines:
res = row.split(",")
if len(res) < 3 or len(res) > 3:
print ("Improper row.")
continue
if res[1].endswith(".jpg") == False and res[1].endswith(".png") == False:
print ("Image not found.")
continue
try:
location = f"C:/Desktop/Images/{res[0]}/"
urllib.request.urlretrieve(res[2], location + res[1].split("/")[-1])
print (f"Saved {res[1].split('/')[-1]} to {location[:-1]}.")
except:
print ("An error occured.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.