0

I have a torrent file obtained by using requests.get() stored in a string and obtained like this:

import requests
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept-Charset': 'utf-8',
'Connection': 'keep-alive'}
request = requests.get(url, headers=headers)
data = requests.text

I would like to write it to a binary file so that the data within it are correct and it is valid:

with open(name, "wb") as f:
    f.write(data)

However I seem to not be able to write the string as pure binary data because python keeps trying to interpret it as Unicode and I get errors like: "UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-9: ordinal not in range (128).

I have attempted to use bytearray but a similar problem arises: TypeError: unicode argument without an encoding.

Is there a way to just write the bytes in the string to a file as they are?

2
  • Are you opening the file in binary mode? Commented Oct 16, 2015 at 19:32
  • 2
    Add the code you are using Commented Oct 16, 2015 at 19:34

1 Answer 1

9
  • Use response.content, not response.text.
  • Use "wb" to open the file for binary output.

Sample program:

import requests

r = requests.get("http://httpbin.org/image/png")
with open("image.png", "wb") as out_file:
    out_file.write(r.content)

A slightly fancier program with a smaller memory footprint for ginormous files:

import requests
import shutil

r = requests.get("http://httpbin.org/image/png", stream=True)
with open("image.png", "wb") as out_file:
    shutil.copyfileobj(r.raw, out_file)
Sign up to request clarification or add additional context in comments.

1 Comment

you probably want r.raw.decode_content = True, to handle Content-Encoding header.

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.