from pathlib import Path
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.
= "./a-new-dir" # Note: This folder does not yet exist
dirname = Path(dirname) path
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:
= path/"a-great-file.txt" filepath
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:
"Hello world, this is so much fun!") filepath.write_text(
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:
filepath
PosixPath('a-new-dir/a-great-file.txt')
# unlink means remove in this context filepath.unlink()
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:
= Path(".") # dot means current dir current
current.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.
12.3 Shutil
🚧 Material under construction 🚧