A read-only open() context manager
You have a bunch of data files for your next deep learning project that took you months to collect and clean. It would be terrible if you accidentally overwrote one of those files when trying to read it in for training, so you decide to create a read-only version of the open()
context manager to use in your project.
The regular open()
context manager:
- takes a filename and a mode (
'r'
for read,'w'
for write, or'a'
for append) - opens the file for reading, writing, or appending
- yields control back to the context, along with a reference to the file
- waits for the context to finish
- and then closes the file before exiting
Your context manager will do the same thing, except it will only take the filename as an argument and it will only open the file for reading.
This is a part of the course
“Writing Functions in Python”
Exercise instructions
- Yield control from
open_read_only()
to the context block, ensuring that theread_only_file
object gets assigned tomy_file
. - Use
read_only_file
's.close()
method to ensure that you don't leave open files lying around.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
@contextlib.contextmanager
def open_read_only(filename):
"""Open a file in read-only mode.
Args:
filename (str): The location of the file to read
Yields:
file object
"""
read_only_file = open(filename, mode='r')
# Yield read_only_file so it can be assigned to my_file
____ ____
# Close read_only_file
____.____()
with open_read_only('my_file.txt') as my_file:
print(my_file.read())
This exercise is part of the course
Writing Functions in Python
Learn to use best practices to write maintainable, reusable, complex functions with good documentation.
If you've ever seen the "with" keyword in Python and wondered what its deal was, then this is the chapter for you! Context managers are a convenient way to provide connections in Python and guarantee that those connections get cleaned up when you are done using them. This chapter will show you how to use context managers, as well as how to write your own.
Exercise 1: Using context managersExercise 2: The number of catsExercise 3: The speed of catsExercise 4: Writing context managersExercise 5: The timer() context managerExercise 6: A read-only open() context managerExercise 7: Advanced topicsExercise 8: Context manager use casesExercise 9: Scraping the NASDAQExercise 10: Changing the working directoryWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.