from pathlib import Path9 Read/Write Files
9.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.
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"filepathPosixPath('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!'
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:
filepathPosixPath('a-new-dir/a-great-file.txt')
filepath.unlink() # unlink means remove in this contextfilepath.exists()False
9.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 dircurrent.is_file()False
current.is_dir()True
Explore the methods of the Path class by creating and object and hitting the Tab key, there are several handy functionalities included.
9.3 Shutil
🚧 Material under construction 🚧
9.4 Exercises
Now that we now how to read files from within python, we can tidy up things a bit from previous chapter.
- Download the data from the repository here into a local file on your computer.
- Write a function that takes a path and returns the list of dictionaries from exercise 8.5. Read the file content using
pathlib.