June 2017
Beginner
352 pages
8h 39m
English
Sometimes you need to perform a clean-up action irrespective of whether an operation succeeds. In a later module we'll introduce context managers which are the modern solution to this common situation, but here we'll introduce the try … finally construct, since creating a context manager can be overkill in simple cases. In any case, an understanding of try … finally is useful for making your own context managers.
Consider this function, which uses various facilities of the standard library os module to change the current working directory, create a new directory at that location, and then restore the original working directory:
import osdef make_at(path, dir_name): original_path = os.getcwd() os.chdir(path) os.mkdir(dir_name) ...
Read now
Unlock full access