🚠 The Pathlib Module¶
The pathlib
module in Python provides various classes representing filesystem paths with semantics appropriate for different operating systems. It's an object-oriented way to handle file paths.
1. Importing the pathlib Module¶
You can import the pathlib
module as follows:
from pathlib import Path
2. Creating Paths¶
With pathlib
, you create paths using the Path
class:
# Create a path to the current directory
p = Path('.')
# Create a path to a file
p = Path('my_file.txt')
# Create a path to a directory
p = Path('/path/to/directory')
3. Joining Paths¶
You can join paths using the /
operator:
p = Path('/path/to')
# Join paths
full_path = p / 'directory' / 'my_file.txt'
print(full_path) # outputs: '/path/to/directory/my_file.txt'
/path/to/directory/my_file.txt
4. Navigating Paths¶
You can navigate paths using various methods, such as:
p = Path('/path/to/directory/my_file.txt')
# Get the parent directory
parent = p.parent
# Get the file name
name = p.name
# Get the file stem (name without extension)
stem = p.stem
# Get the file extension
suffix = p.suffix
print(parent) # outputs: '/path/to/directory'
print(name) # outputs: 'my_file.txt'
print(stem) # outputs: 'my_file'
print(suffix) # outputs: '.txt'
/path/to/directory my_file.txt my_file .txt
5. Checking Path Properties¶
You can check if a path exists, if it's a file or if it's a directory:
p = Path('/path/to/directory/my_file.txt')
# Check if the path exists
print(p.exists()) # e.g., outputs: True
# Check if the path is a directory
print(p.is_dir()) # e.g., outputs: False
# Check if the path is a file
print(p.is_file()) # e.g., outputs: True
False False False
6. Reading and Writing Files¶
You can read and write files (although it is preferred to use the built-in open() function):
p = Path('my_file.txt')
# Write to a file
p.write_text('Hello, world!')
# Read from a file
text = p.read_text()
print(text) # outputs: 'Hello, world!'
Hello, world!
7. Creating Directories¶
creates the folder and all parent folders if needed, without raising an error if it already exists
folder = Path('my_folder')
folder.mkdir(exist_ok=True, parents=True)
The pathlib
module provides a more comfortable way to work with paths compared to the os.path
module. It's especially helpful if you're working with paths where the directory separator changes between operating systems, because it always uses the correct one automatically.