Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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.