0% found this document useful (0 votes)
28 views

Context Manager

This document discusses context managers in Python. Context managers allow efficient allocation and release of resources like files. The document explains how to use the 'with' statement and open() function to read from and write to files using context managers, avoiding issues around forgetting to close files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Context Manager

This document discusses context managers in Python. Context managers allow efficient allocation and release of resources like files. The document explains how to use the 'with' statement and open() function to read from and write to files using context managers, avoiding issues around forgetting to close files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

4/25/24, 10:37 PM Notebook.

ipynb - Colab

keyboard_arrow_down Context Managers


Context managers are a type of object that you can use to properly manage
resources. When you're working with files for example, it's important to open a file,
and then close it again when you're done using it, regardless of whether your code
ran successfully or encountered an error. Context managers help with this by
providing a quick way to allocate and release resources precisely when you need
them.

Motivations

Learning about context managers will allow you to:

Efficiently allocate and release resources


Minimise errors during file handling
Understand how to read from and write to files effectively

keyboard_arrow_down Example: File Handling


A common problem in programming is that resources, such as files, directories, connections,
etc., are retained indefinitely. Proper resource management is often a challenge. It requires both
setup and cleanup phases.

Let's use reading and writing from files as an example. Python has a function called open , which
assigns a file object to a variable, so that you can perform some task such as reading from or
writing to the file. We call that variable that refers to a file object a "file handle". To write some
data to a file, you must first call open on the filepath:

file = open("hello.txt", "w")


file.write("Hello, World!")
file.close()

If a file is updated without closing it, the data will not be stored in the target file. In the code
block below, the string Will i be stored in the file? has not yet been saved to hello.txt .

file = open("hello.txt", "w")


file.write("Will I be stored in the file?")

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/32. Context Manage… 1/3


4/25/24, 10:37 PM Notebook.ipynb - Colab

29

To save it, you must also release the file handle using the . close() method:

file.close()

# check that the data is in the file:


file = open("hello.txt", "r")
print(file.read())

Will I be stored in the file?

You can avoid the risk of forgetting to close the file (and thereby failing to save your data) by
using context managers. Python uses the with keyword to denote the start of a context
management code-block. Context managers have the following syntax:

with expression as target_var:


do_something(target_var)

For example, to open and close a file, you could use:

with open("hello.txt", mode="w") as file:


file.write("I come from the context manager, nice to meet you")

This is telling the Python interpreter that, during the following codeblock (and only that
codeblock), the interpreter should open the hello.txt file object in write ( w ) mode, and assign
it to the variable file . Once the indented block following the with statement is finished, this
will no longer be the case. The file variable will no longer be associated with that context, and
the file object will be closed.

Other Modes of the open Function

As well as w for write, there are various other update modes for the open function. Here is a full
list of the options:

'r' (Read Mode): Default mode, opens a file for reading


'w' (Write Mode): Opens a file for writing, creates a new file if it doesn't exist
'x' (Exclusive Creation): Creates a new file, fails if the file already exists
'a' (Append Mode): Opens a file for appending, creates a new one if it doesn't exist
'b' (Binary Mode): Used with other modes for interacting with binary files (e.g., 'rb' ,
'wb' )

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/32. Context Manage… 2/3


4/25/24, 10:37 PM Notebook.ipynb - Colab

't' (Text Mode): Used with other modes for interacting text files (e.g., 'rt' , 'wt' ),
usually not needed as it represents default behaviour
'+' (Update Mode): Used with other modes to read and write to the same file

keyboard_arrow_down Key Takeaways


Context Managers are useful for efficient and error-free resource handling
The with statement defines the start of a context management code block
The with statement assigns an expression to a variable for the duration of the indented
block following it
You can use with open(filename) to manage reading from and writing to files
There are different modes for the open function, depending on the action you wish to
perform on the file

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/32. Context Manage… 3/3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy