Files and Directories
Context managers can be found throughout the standard library and often are an alternate way of doing something. In the previous lesson, I showed opening a file in both the
except way and the context manager way. In this lesson, I’m going to run you through two practical uses.
The first will give more details on opening files, and the second will show you how to use
os.scandir() to iterate through the contents of a directory. In the previous lesson, I quickly spoke about reading from one file and writing to another.
Let’s take a look at some actual code that does this. On the screen is
ohno.py. It takes a file name as a command-line argument, opens that file, reads each line of the file into a string, replaces all the
"o"s in the string with a not sign (
"🚫"), then writes the new string into a different file.
It’s much cleaner. On this line, I take the first command-line argument and use it to build a
Path object. In a real program, I would have a bunch of error-checking here to make sure the file exists.
The only difference is the built-in function takes the filename as an argument. With the
Path object, this method calls the built-in
open() function for you, passing in the filename contained in the
"x", which is exclusive write. If the file already exists, this will throw an exception, hence why all of this is wrapped in a
try block. Lines 10 through 12 do the data transformation, reading each line from the
src file handle, doing the
.replace() call, then writing each line into the
dest file handle.
Become a Member to join the conversation.