12  Read/Write Files

12.1 Pathlib

We often deal with files stored in our computer (or someone else’s, a.k.a. “the Cloud”). The built-in pathlib is very a useful module. In particular, the Path class simplifies a lot the operations we typically do when working with files.

from pathlib import Path
dirname = "./a-new-dir"  # Note: This folder does not yet exist
path = Path(dirname)
path.exists()
False

Let’s create it:

path.mkdir()
path.exists()
True

Notice how the Path instance composes very nicely with the rest of the language. For example, it will automatically concatenate the path with this syntax:

filepath = path/"a-great-file.txt"
filepath
PosixPath('a-new-dir/a-great-file.txt')
filepath.exists()
False

Let’s create it:

filepath.touch()
filepath.exists()
True

This file is still empty, let’s write a message into it:

filepath.write_text("Hello world, this is so much fun!")
33

A lot just happened:

  • the file was created
  • we opened the file
  • we wrote the text into it
  • we closed the file
  • we got back the number of bytes written (33)

So the Path class is abstracting away a lot of work. Pretty handy, I think.

Now let’s read in the content of the file:

filepath.read_text()
'Hello world, this is so much fun!'
Note

The classical way to open/close files is actually using the open function. You can google it if you’re curious, but, for now, let’s run with pathlib.Path.

We can also delete files/directories:

filepath
PosixPath('a-new-dir/a-great-file.txt')
filepath.unlink()  # unlink means remove in this context
filepath.exists()
False

12.2 Files & Directories

When manipulating files we sometimes we want to explicitly distinguish between files and directories. pathlib.Path has a few methods that make our life easier:

current = Path(".")  # dot means current dir
current.is_file()
False
current.is_dir()
True
Tip

Explore the methods of the Path class by creating and object and hitting the Tab key, there are several handy functionalities included.

12.3 Shutil

🚧 Material under construction 🚧