The Ultimate Swiss Army Knife for Handling Files and Directories in Python!
Python’s pathlib library is a module that provides an object-oriented approach to working with file paths and directories in a platform-independent manner. It was introduced in Python 3.4 and offers a more intuitive way of working with files and directories than the traditional os.path module.
Pathlib allows you to manipulate paths as if they were objects, which makes it easier to work with file system paths and reduces the risk of errors that can arise when manually constructing or manipulating strings. It provides a set of classes to represent file paths, along with various methods for accessing and manipulating the files and directories.
I’ve prepared a cheat sheet of all the important pathlib functions and everything that you’ll ever need to make yourself super-productive.
CheatSheet
from pathlib import Path
# Creating a new Path object
path = Path('directory/subdirectory/filename.txt')
# Getting the file name
path.name # 'filename.txt'
# Getting the parent directory
path.parent # PosixPath('directory/subdirectory')
# Checking if a path exists
path.exists() # True
# Checking if a path is a file
path.is_file() # True
# Checking if a path is a directory
path.is_dir() # False
# Getting the absolute path
path.absolute() # PosixPath('/home/user/directory/subdirectory/filename.txt')
# Joining two paths together
path = Path('directory') / 'subdirectory' / 'filename.txt'
# Iterating over all files in a directory
directory_path = Path('directory')
for file_path in directory_path.iterdir():
print(file_path)
# Creating a new directory
new_directory_path = Path('new_directory')
new_directory_path.mkdir()
# Creating a new file and writing to it
new_file_path = new_directory_path / 'new_file.txt'
with open(new_file_path, 'w') as f:
f.write('Hello, world!')
# Reading from a file
with open(path, 'r') as f:
contents = f.read()
print(contents)
Example: Get all files with extension .txt in current directory
from pathlib import Path
# Get the current directory
directory = Path.cwd()
# Use glob to find all .txt files in the current directory
txt_files = directory.glob('*.txt')
# If you want to find all .txt files in current directory and all
# subdirectories recursivley then you can use rglob method instead of glob
# Loop through the files and print their names
for file in txt_files:
print(file.name)
Example: Creating new directories and files
from pathlib import Path
# Create a new directory
new_dir = Path('/path/to/new/directory')
new_dir.mkdir(parents=True, exist_ok=True)
# Create a new file in the directory
new_file = new_dir / 'new_file.txt'
new_file.write_text('Hello, world!')
Example: Checking if a file exists
from pathlib import Path
# Check if a file exists
file_path = Path('/path/to/file.txt')
if file_path.exists():
print('The file exists!')
else:
print('The file does not exist.')
Example: Get parent directory of a file
from pathlib import Path
# Get the parent directory of a file
file_path = Path('/path/to/file.txt')
parent_dir = file_path.parent
# Print the name of the parent directory
print(parent_dir.name)
Example: Getting size of a file
rom pathlib import Path
# Get the size of a file
file_path = Path('/path/to/file.txt')
file_size = file_path.stat().st_size
# Print the size of the file
print(f'The file size is {file_size} bytes.')
Got more examples? Do share them in the comments!