How to use the Pathlib Module in Python | QuickStart Guide for Beginners
pathlib replaces os.path string juggling with Path objects: join paths with the slash operator, read and write files with methods on the path itself, and glob a directory in one call. It also handles Windows and POSIX separators for you.
Importing the main class:
from pathlib import Path
Get the home directory
home_dir = Path.home()
Get the path to the current working directory
cwd = Path.cwd()
Get the path to the current Python file (does not work in Jupyter Notebooks)
curr_file = Path(__file__)
Get the first parent folder path
one_above = Path.cwd().parent
Get the Nth parent folder path
mul_above = Path.cwd().parents[0]
Join paths
joined_path = cwd / 'Output'
Create a directory if it does not exist
joined_path.mkdir(exist_ok=True) # exist_ok: to ignore 'FileExistsError'if the target directory already exists
Check if the path is a folder
joined_path.is_dir()
Check if the path is a file
example_file = cwd / "somefile.txt"
Get the file name
file_name = example_file.name
Get the file name w/o extension
file_name = example_file.stem
Get the file extension
file_extension = example_file.suffix
Iterate over files in a directory
target_dir = cwd / "Sample Files"
for file in target_dir.iterdir():
print(file)Iterate over files in a directory combined with suffix
for file in target_dir.iterdir():
if file.suffix == ".xlsx":
print(file)Iterate over files in a directory incl. sub folder(s)
for file in target_dir.rglob("*"):
print(file)