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.
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.
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.
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.
Become a Member to join the conversation.