Home > Software engineering >  How do you name image files using a second column in the CSV file when using urllib?
How do you name image files using a second column in the CSV file when using urllib?

Time:05-30

I have a list of 100 images I want to download in a CSV file. There are no headers on the CSV. The first column has the location of the image and the second column has the name I would like the image saved as.

I am using urllib to download the images. I would like to setup a for loop which uses the location from the first column and names it from the data in the second column. The line I put in here is wrong, but hopefully you get the idea - urllib.request.urlretrieve('url[0]', 'url[1]') - I'm trying to pull from the first or second column.

urls = []
f = open('multicoltest.csv', encoding='utf-8-sig')
csv_f = csv.reader(f)

for row in csv_f:
    urls.append(row[0])
f.close()

for url in urls:
    urllib.request.urlretrieve('url[0]', 'url[1]')

CodePudding user response:

You can do it a line at a time without reading the entire file first:

with open('multicoltest.csv', encoding='utf-8-sig') as f:
    for row in csv.reader(f):
        urllib.request.urlretrieve(row[0], row[1])
  • Related