1

I am trying to save the image file got by requests.get()

def get_image_file(class_path,image_id):
    r = requests.get(BASE_REQUEST_URL+'/image/'+image_id+'/download',  stream=True)
    print(r.url)
    if r.status_code == 200:
        with open(IMAGE_PATH+class_path+str(INCR)+'.jpg', 'wb+') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)
            print("Image saved")
    else:
        print('Can not save the image.')

So, if image is benign, image will go to 'benign' folder. When I call the function

get_image_file('benign/','5436e3acbae478396759f0d5')

Here what I get:

https://isic-archive.com/api/v1/image/5436e3acbae478396759f0d5/download
Traceback (most recent call last):
File "image_fetch.py", line 59, in <module>
   get_image_file('benign/','5436e3acbae478396759f0d5')
File "image_fetch.py", line 34, in get_image_file
     with open(IMAGE_PATH+class_path+str(INCR)+'.jpg', 'wb+') as f:
FileNotFoundError: [Errno 2] No such file or directory:   '~/tf_files/benign/0.jpg'

I thought the problem is in the write permission.I tried to use 'wb','wb+','a+', but nothing helped.

dulatus
  • 55
  • 2
  • 8
  • 1
    What are the values of `IMAGE_PATH`, `class_path` and `INCR` – ZdaR Feb 15 '17 at 09:22
  • 1
    The file name seems to start with a quote `'` (as you can see there is no closing one). Is it an error when copying the message error or is the quote part of the filename? –  Feb 15 '17 at 09:22
  • IMAGE_PATH = '~/tf_files/', class_path = 'benign/', INCR=0 is the increment which increments each time image downloaded to numerate the images. – dulatus Feb 15 '17 at 09:44
  • @Sembei Norimaki No, quote is just a copy/pasting mistake. – dulatus Feb 15 '17 at 09:54

1 Answers1

2

~/tf_files isn't a valid path, unless you're working in a shell; the ~ gets expanded to your home directory by bash and co., not by the OS. If you want to have tildes in paths in Python, you should run them through os.path.expanduser before doing the open:

path = IMAGE_PATH+class_path+str(INCR)+'.jpg'
path = os.path.expanduser(path)
with open(path, 'wb+') as f:
    # ...
    pass
wildwilhelm
  • 4,809
  • 1
  • 19
  • 24