Home > Software design >  How do I download images to the folder I specify with Python urllib request?
How do I download images to the folder I specify with Python urllib request?

Time:07-31

For example, I want to download the pictures to the folder named pictures. How can I do this with urllib request

import os
import urllib.request
try:
    klasor_yarat = os.mkdir("resimler")
except:
    pass
say = 1
for i in resim_listesi:
    urllib.request.urlretrieve(i,str(klasor_yarat) "\"resim"  str(say)  ".jpg")
    say =1

CodePudding user response:

os.mkdir() doesn't return anything, so klasor_yarat doesn't have any value in your code. Instead, create the path like this:

import os
import urllib.request

resimler = "resimler"

try:
    os.mkdir(resimler)
except:
    pass

say = 1
for i in resim_listesi:
    urllib.request.urlretrieve(i, os.path.join(resimler, "resim"   str(say)   ".jpg"))
    say =1

Use os.path.join() to create paths in a platform-independent way, instead of trying to add slashes yourself.

CodePudding user response:

This should be achievable through specifying the directory inside of your file name/path for the image.

For example:

import os
import urllib

try:
  os.mkdir("directory")
except:
  pass
  
url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png"
urllib.request.urlretrieve(URL, "directory/google.png")

CodePudding user response:

There seem to be several problems here:

  • "\"resim" is not the correct way to put a '/' in the string. You have to use "/" or "\\".
  • str(klasor_yarat) returns "None".
  • You are adding a ".jpg" to the image retrieved. What if the image is a different extension?
  • Make sure resim_listesi is an iterable. I can't know that because it's not defined in the code given.
  • Lastly, try using English names for variables as that will improve the readability of your code for others.

Anyway, this should probably work.

import os
import urllib.request
try:
    klasor_yarat = os.mkdir("resimler")
except:
    pass
say = 1
for i in resim_listesi:
    urllib.request.urlretrieve(i,"resimler/resim"  str(say)  ".jpg")
    say =1
  • Related