0

I am trying to get an image from a website and I don't know what i am doing wrong. Here is my code:

import httplib2

h = httplib2.Http('.cache')

response, content = h.request('http://1.bp.blogspot.com/-KSBzFF0bIyU/TtFyj-KgC0I/AAAAAAAABEo/o43IoY_9Bec/s1600/praia-de-ponta-verde-maceio.jpg')

print(response.status)

with open('maceio.jpg', 'wb') as f:
    print(content, file = f)

--------------------------------------------------------------------------------

 200
Traceback (most recent call last):
  File "/home/matheus/workspace/Get Link/new_method_v2.py", line 12, in <module>
    print(content, file = f)
TypeError: 'str' does not support the buffer interface
pb2q
  • 58,613
  • 19
  • 146
  • 147
matheus
  • 107
  • 8
  • possible duplicate of [TypeError: 'str' does not support the buffer interface](http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface) – Ferdinand Beyer May 31 '12 at 14:13

1 Answers1

2

The error is caused by the following line:

print(content, file = f)

print implicitely converts the bytes object named content to a string (str object), which cannot be written to a file in binary mode, since Python does not know which character encoding to use.

Why are you taking the print detour at all? Just write the contents to the file using the file.write() method:

with open('maceio.jpg', 'wb') as f:
    f.write(content)
Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145