How to Use pathlib in Python: Simple File Path Handling
Use the
pathlib module in Python to work with file paths in an easy and readable way by creating Path objects. You can perform operations like joining paths, checking existence, and reading or writing files using simple methods on these objects.Syntax
The main class in pathlib is Path. You create a Path object by passing a string representing a file or directory path. You can then use methods like exists(), is_file(), mkdir(), and operators like / to join paths.
- Path('some/path'): creates a path object
- path.exists(): checks if the path exists
- path.is_file(): checks if path is a file
- path / 'file.txt': joins paths
python
from pathlib import Path # Create a Path object p = Path('folder') # Join paths file_path = p / 'file.txt' # Check if path exists exists = file_path.exists() # Create directory p.mkdir(exist_ok=True)
Example
This example shows how to create a directory, create a file path inside it, check if the file exists, and write text to the file.
python
from pathlib import Path # Create a directory path folder = Path('example_folder') folder.mkdir(exist_ok=True) # Create a file path inside the directory file = folder / 'hello.txt' # Check if file exists print('File exists before writing:', file.exists()) # Write text to the file file.write_text('Hello, pathlib!') # Check if file exists after writing print('File exists after writing:', file.exists()) # Read and print the file content content = file.read_text() print('File content:', content)
Output
File exists before writing: False
File exists after writing: True
File content: Hello, pathlib!
Common Pitfalls
Some common mistakes when using pathlib include:
- Using string operations instead of
Pathmethods for paths, which can cause errors on different operating systems. - Forgetting to create directories before writing files, causing errors.
- Using
Pathobjects and strings interchangeably without converting.
Always use Path methods and operators for path manipulation.
python
from pathlib import Path # Wrong: joining paths with + operator (raises TypeError) # p = Path('folder') # file = p + 'file.txt' # This is wrong # Right: use / operator to join paths p = Path('folder') file = p / 'file.txt' # Wrong: writing to file without creating directory # file.write_text('text') # May raise error if folder doesn't exist # Right: create directory first p.mkdir(exist_ok=True) file.write_text('text')
Quick Reference
| Method/Operator | Description |
|---|---|
| / | Join paths easily, e.g. Path('a') / 'b' -> 'a/b' |
| exists() | Check if path exists |
| is_file() | Check if path is a file |
| is_dir() | Check if path is a directory |
| mkdir(exist_ok=True) | Create directory, no error if exists |
| write_text(text) | Write text to file |
| read_text() | Read text from file |
| name | Get the file or folder name |
| parent | Get the parent directory path |
Key Takeaways
Use pathlib.Path objects to handle file paths in a clear and cross-platform way.
Join paths with the / operator instead of string concatenation.
Always create directories before writing files to avoid errors.
Use pathlib methods like exists(), is_file(), write_text(), and read_text() for common file operations.
Avoid mixing strings and Path objects without conversion to prevent bugs.