Eugeen
Eugeen

Reputation: 51

Downloading images in python with a directory in the link?

I have an image on a website: (example)

www.testing.com/hello/subfolder/the%20martian%20movie.jpg

When attempted to download this image to my chosen directory (Users/Home/Temp) in my python program, it picks up on '/subfolder'. How can I ignore this without affecting my other images that I have discovered? This one image is the only one that has a directory in front of it, all other jpg images will display the correct link and take me to the image and download it to my temp folder, just not this one and this one is the only one with a directory in its name.

This is the code I am using:

for jpg in jpg_list:
    os.path.basename(jpg)
    print(jpg)
    fullfilename = os.path.join(f'{dl_location}', f'{jpg}')
    dl_link = url + jpg

    if os.path.isfile(fullfilename):
        print('file already exists, renaming.')
        os.rename(fullfilename, f'{fullfilename}-copy{c}.jpg')
        c=c+1

    urllib.request.urlretrieve(dl_link, fullfilename)

in the for loop I have attempted to use basename with no such luck, it still picks up on the /subfolder and I think tries to create the subfolder, but the '/subfolder' is part of the image link!

I receive the error message

FileNotFoundError: [Errno 2] No such file or directory: '/Users/Home/Temp/CW/subfolder/The%20Martian%20-%20image.jpg'

Upvotes: 0

Views: 266

Answers (1)

netniV
netniV

Reputation: 2418

I suspect the reason is that you are not assigning the output of basename into a variable. Thus you are never actually using the base version of your filename.

jpg = os.path.basename(jpg)

Upvotes: 1

Related Questions