The Path class provides functions for manipulating paths.
path should be a string, list, tuple, or Path object. Most likely, it will be a string, which creates a new Path object that represents that path. An example would be Path("/usr/bin").
Note that all new Path objects automatically:
- Expand ~ and ~user
- Expand $ENV_VAR and %WINDOWS_MUST_BE_DIFFERENT% variables
- Make the path absolute
- Remove double slashes (a//b), .‘s, and ..‘s
- Normalizes case, if necessary.
Symbolic links are not, however, removed from the path.
The Path object can be used in many ways. Assuming path is Path object:
path + "dir/dir" – Paths can be added to strings to yield new paths
if path: ... – Paths are True if they exist
len(path); path[i] – Paths can be used as a list. Note that for a Unix environment, Path[0] will be Path(/). This can be a bit confusing. For example, Path("/usr/local/bin")[2] is Path(/usr/local). Its as if Path objects use one-based indexing, and you can think of it that way if you want.
path[-1] = "bob" also works, as does path[1:4] = "usr/local/share". So does del path[2].
"file" in path – Is a file in that path?
str(path) – Returns the path in string form. This always does not contain the final slash.
with path: ... – This will change directory to path before entering the with loop, and change back afterwards.
Of course, a :class:Path object also has some useful methods. These are detailed below.