Path Handling Using Python

What is effectively a path?
In computer science, a path is a string or object that describes the location of a file or directory in a filesystem. Paths are essential for reading or writing files, navigating directories, and referencing resources.
What types of paths exist?
Absolute Path
An absolute path points to a resource from the root of the filesystem.
# Windows
C:\Users\Andrew\Projects\app\main.py
# Unix-based
/home/andrew/projects/app/main.py
Relative Path
A relative path is relative to the current working directory (it is also known as
cwd
), or the script’s directory depending on usage.
./main.py # current directory
../main.py # one level up
src/utils.py # relative subfolder
An example with Python of both:
The example is fairly self-explanatory, however for those who do not understand it, they use the is_absolute()
function by referring it to the type of path will be given a boolean value if the path is absolute or not (it means relative).
from pathlib import Path
# Absolute path
absolute_path = Path("C:/Users/Andrew/Projects/app/main.py")
print(absolute_path.is_absolute()) # True
# Relative path
relative_path = Path("src/utils.py")
print(relative_path.is_absolute()) # False
Now let's take a look at the pathlib
library!
Python’s pathlib
provides a modern, object-oriented API for filesystem paths. We will only take a look at pathlib.Path
. The following is the import of the library.
from pathlib import Path
What is Path(file)
?
The __file__
variable is a built-in variable containing the path of the current script. Wrapping it in Path()
gives you a Path
object pointing to the script file.
script_path = Path(__file__)
What is resolve()
?
The resolve()
method converts the path to an absolute, canonical version, resolving any symlinks and ..
segments.
How to go through the directories?
The parent
property returns the parent directory of the current path. Useful for locating project roots or placing output directories or files relative to the script location.
# So this is for the directory where the source file is where the statement is written.
base_directory = Path(__file__).resolve().parent
# So this is for the parent directory of the directory where the source file is where
# the statement is written.
grandparent_directory = Path(__file__).resolve().parent.parent
# And so on.
What is joinpath()
?
The joinpath()
method is used to concatenate one or more segments to the current path, creating a new Path object.
base = Path("/home/andrew")
path1 = base.joinpath("project", "main.py")
But there is a more expert way to concatenate one or more segments to the current path, it is with the /
operator, but be careful, not with simple strings or it will give error.
path_like_a_pro = base / "project" / "main.py"
How to do safe directory creation?
Creates the directory. If it exists, no exception is raised if exist_ok=True
.
output_dir = Path(__file__).resolve().parent / "output"
output_dir.mkdir(exist_ok=True)
Another useful flag is parents=True
which creates all parental directories if needed.
How to create a file in that directory?
log_file = output_dir / "log.txt"
log_file.write_text("This file was created via pathlib.\n")
Subscribe to my newsletter
Read articles from AndrewFox_DEV directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
