Search code examples
pythonpython-requestspython-3.9

Can mode='wb' in python I/O operations write image binaries


see my pc screen the piece of code I used is this:

from wikipedia import page
import requests

responce = requests.get(page('beach').images[0])

with open(r'files/beach.jpg', mode='wb') as file:
    file.write(responce.content)

but it always endup making a file which photo viewer can not open

python version 3.9.6, modules installed wikipedia:1.4.0, requests:2.26.0

it is running perfectly fine on my machine without any error


Solution

  • Please check if the below code works as per your requirement. The problem with your code is that you are just writing the raw content of the Wikipedia HTML page to files/beach.jpg file in binary mode and it isn't a valid image file. To understand better, try renaming the image file created by your earlier code to beach.txt and see the content.

    from wikipedia import page
    from urllib.request import urlretrieve
    
    urlretrieve(page('beach').images[0], "files/beach.jpg")