How to use the Pathlib Module in Python | QuickStart Guide for Beginners
In this quick tutorial, I am going to show you how to use the Pathlib module in Python. If you are new to Python, this will give you a quick introduction to the most widely used Python module for path manipulations. I will show you how to work with file paths & directories and how to list all files and folders in a directory.
📝 Resources:
- Download the Jupyter Notebook here: https://github.com/Sven-Bo/pathlib-quickstart-guide
- FREE Pathlib Cheat Sheet: https://pythonandvba.com/pathlib-cheat-sheet
👩💻 Source Code:
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)