Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using the With Statement

Download link from this lesson: https://api.worldbank.org/v2/en/indicator/NY.GDP.MKTP.CD?downloadformat=csv

00:00 The safest way to open and write to files in Python is by using the with statement. This is known as a context manager. It ensures that your file is properly closed as soon as the code block finishes, even if an error occurs while writing.

00:14 This prevents issues where files stay locked or resources get leaked. Let’s look at how you can save the file using a simple code example.

00:23 In the previous lesson, you imported requests, you defined the download URL, you defined query parameters, and you downloaded the file. Now to save this file, just type with open(), and in the open() function, the first parameter is the name that you want your saved file to have.

00:42 So I’ll just write country_gdp.zip.

00:47 And the second parameter is the mode in which you want to open the file. It takes a string, and just type "wb" here. And after the open() function, write as file, which assigns a handle to the file that’s just opened.

01:02 And you can use this handle called file later on in the code. Now, what actually is "wb"? This stands for write binary.

01:12 When you download files like images, PDFs, or zips, they’re not just plain text, they’re raw byte data. If you try to save them as text, Python might try to encode them, which can corrupt the file.

01:24 So that’s why you use "wb" so that your files like PDFs, zips, images, or any other binary file isn’t corrupted. Just hit Enter and type file.write().

01:37 And to the file country_gdp.zip, you want to write your response content, right? So just type response.content.

01:48 And now the content of the response will be written to file and you’ll have your zip. Let’s exit from the REPL session and see if the file is actually downloaded.

01:59 You can list files from a terminal and notice that the file is actually downloaded.

02:06 Now let’s break down what you just did. You imported requests, you defined a URL, and then you downloaded the content from the URL using the .get() function. And after that, you used the context manager called with to open a local file.

02:21 You passed "wb" as the second argument, and then you wrote response.content to it. response.content gives you the raw bytes directly from the server.

02:30 If you had used response.text here instead of response.content, requests would’ve tried to decode the binary data into a string, which would’ve likely resulted in a broken file.

Become a Member to join the conversation.