Reading and Writing Files
Reading and Writing Files. Traditionally, the way to read or write a file in Python has been to use the built-in open function. This is still true, as the
open() function can use
Path objects directly.
00:15 The example seen on-screen finds all headers in a Markdown file and prints them.
An equivalent alternative is to call
.open() on the
Path.open() is calling the built-in
open() behind the scenes. Which option you use is mainly personal preference. For simple reading and writing of files, there are a few convenience methods in the
.read_text() opens the path in text mode and returns the contents as a string.
.read_bytes() opens the path in binary and bytes mode and returns the content as a bytestring.
.write_text() opens the path and writes string data to it.
.write_bytes() opens the path in binary/bytes mode and writes data to it. Each of these methods handles the opening and closing of the file, making them trivial to use, as seen on-screen.
01:59 Paths can also be specified as simple filenames, in which case they are interpreted relative to the current working directory. The example you’re seeing now is equivalent to the one you just saw.
.resolve() method will find the full path. You can confirm that the current working directory is used for simple filenames.
Note that when the paths are compared, it’s their representations that are compared. Here,
path.parent is not equal to
path.parent is represented by
. (dot), while
pathlib.Path.cwd() is represented by the full path to the directory.
02:55 In the next section of the course, you’ll take a look at moving and deleting files.
Become a Member to join the conversation.