Python: Trees
Theory: Manipulating the virtual file system
The library we use to build trees is designed only for immutable file structures. It means we cannot change it once we create it. But it is possible to make a new one based on the old one and modify some parts.
We deliberately chose to use an immutable structure for this course. This structure is easier to debug, and you're less likely to make mistakes. And it allows you to immerse yourself as much as possible in higher-order functions.
Basic operations with nodes
The python-immutable-fs-trees package allows you to create trees and extract data from previously created files and directories. It means you don't have to crawl through the internal structure of the tree itself:
Additionally, the package has two functions for checking types. Using them, you can selectively work with files and directories:
The operations we have looked at are enough to perform any transformations on files and directories. Let us start with the simplest ones, which don't require recursive traversal.
Processing
Any processing in an immutable style boils down to new data formation based on old ones. Below, we'll implement some conversion options that say more about this idea. Changing the file name looks like this:
A new file is created here with the metadata of the old. Before we created a new file, we cloned metadata by deep cloning. Why? We pass dictionaries by reference. If we do not clone, the new file will contain the metadata of the old one. If we want to change something, changing the new one means breaking the old one:
Sorting the contents of a directory looks like this:
Updating the contents of a directory looks like this:
Deleting files within a directory looks like this: