[ Invalid filename or mode 'wb' ]

I am using django. I was trying to compress an icon uploaded by a user to a smaller size using Pythons Image library.

Following is my code:

def resizeImage(icon,ext):
     path= os.path.join(settings.SITE_ROOT,'karnadash/static/tempfiles/temp'+ext)
     destination = open(path,'wb+')
     for chunk in icon.chunks():
         destination.write(chunk)
     destination.close()
     image = Image.open(path)
     image= image.resize((50, 50), Image.ANTIALIAS)
     image.save(path)
     return image

Problem is I am getting an internal server error. The last part of the stack trace is as follows:

 line 31, in resizeImage
     image.save(path)
 File "C:\Python27\lib\site-packages\PIL\Image.py", line 1446, in save
     fp = builtins.open(fp, "wb+")
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:/Users/Silent/Documents/Python/karnadash/karnadash/static/tempfiles/temp.jpg'

Can anybody please explain why this is happening?

Answer 1


What solved it for me was switching from backslashes to forward slashes! Who would've thought?!

Similar post: ioerror invalid mode w

Answer 2


Check your file path if it's valid:

C:/Users/Silent/Documents/Python/karnadash/karnadash/static/tempfiles/temp.jpg

Perhaps it contains one karnadash too much.