Reading and Writing Files
00:00
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.
00:44
An equivalent alternative is to call .open()
on the Path
object.
01:06
In fact, 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 pathlib
library. .read_text()
opens the path in text mode and returns the contents as a string.
01:28
.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.
01:38
.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.
02:14
The .resolve()
method will find the full path. You can confirm that the current working directory is used for simple filenames.
02:33
Note that when the paths are compared, it’s their representations that are compared. Here, path.parent
is not equal to pathlib.Path.cwd()
, because 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.