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
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! If possible, can you talk a little more about the "g.write()" ?
Have a look at the documentation: docs.python.org/library/stdtypes.html#file.write

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.