Go From Bytes to File
Below that is the
with statement that passes in
example.com and sets the
body variable to
response.read(). To write the bytes directly to a file without having to encode, you’ll need the built-in
open() function, and you’ll need to ensure that you use write binary mode.
And you’ll be opening it as an
html_file. And then you write the body to the file with
html_file.write() and pass in the
body variable that was previously set on the response object with the
To run the script, type
py urllib_requests.py. You may notice that you do not see any output. If you type
ls, which stands for list, into your terminal, this will list the files and directories in the current directory.
02:16 That’s it. You’ve written the bytes directly to a file without encoding or decoding anything. Now say you have a URL that doesn’t use UTF-8, but you want to write the contents to a file with UTF-8.
This will attempt to determine the character set of the content by reading the
Content-Type header of the response. You can set the variable
content equal to
body.decode() and pass in the
This will decode the body using the detected character set. To save the content to the file, you can type out
with open("google.html", encoding="utf-8", mode="w")
as file and write to the file with
file.write() and pass in
Become a Member to join the conversation.