The pathlib
module in Python provides an object-oriented approach to working with file system paths. It is a modern alternative to the os
and shutil
modules and simplifies file and directory handling.
Why Use pathlib
?
- More readable and concise than
os.path
functions. - Works seamlessly with Windows, macOS, and Linux.
- Provides an object-oriented interface for paths.
- Supports file operations, directory traversal, and path manipulation.
Importing pathlib
from pathlib import Path
1. Creating Path Objects
1.1 Current Directory (cwd()
)
from pathlib import Path
current_path = Path.cwd() # Get current working directory
print(current_path)
Output (Example)
/home/user/projects
1.2 Home Directory (home()
)
home_path = Path.home() # Get the home directory
print(home_path)
Output (Example)
/home/user
1.3 Creating a Custom Path
custom_path = Path("/home/user/documents/file.txt")
print(custom_path)
Output
/home/user/documents/file.txt
2. Checking if a File or Directory Exists
2.1 Check if Path Exists
path = Path("example.txt")
print(path.exists()) # True if file/directory exists
2.2 Check if Path is a File
print(path.is_file()) # True if it's a file
2.3 Check if Path is a Directory
dir_path = Path("/home/user/documents")
print(dir_path.is_dir()) # True if it's a directory
3. Creating Directories and Files
3.1 Create a Single Directory
new_dir = Path("new_folder")
new_dir.mkdir(exist_ok=True) # Create directory (no error if it exists)
3.2 Create Nested Directories
nested_dir = Path("parent/child/grandchild")
nested_dir.mkdir(parents=True, exist_ok=True) # Create all parent directories
3.3 Create an Empty File
file_path = Path("example.txt")
file_path.touch() # Creates an empty file if it doesn't exist
4. Listing Files and Directories
4.1 List All Files in a Directory
directory = Path(".") # Current directory
for file in directory.iterdir():
print(file)
4.2 List Only Files
for file in directory.iterdir():
if file.is_file():
print(file)
4.3 List Only Directories
for folder in directory.iterdir():
if folder.is_dir():
print(folder)
4.4 Use glob()
for Pattern Matching
for file in Path(".").glob("*.txt"): # Find all .txt files
print(file)
4.5 Use rglob()
for Recursive Search
for file in Path(".").rglob("*.py"): # Find all Python files in subdirectories
print(file)
5. Reading and Writing Files
5.1 Read File Contents
file_path = Path("example.txt")
print(file_path.read_text()) # Read the file content as a string
5.2 Write to a File
file_path.write_text("Hello, World!") # Overwrites the file with new content
5.3 Append to a File
with file_path.open(mode="a") as file: # Append mode
file.write("\nNew line added!")
6. Copying, Moving, and Deleting Files
6.1 Copy a File (shutil.copy
)
import shutil
source = Path("example.txt")
destination = Path("backup.txt")
shutil.copy(source, destination) # Copy file
6.2 Move or Rename a File
source.rename("new_name.txt") # Rename or move file
6.3 Delete a File
file_to_delete = Path("unnecessary.txt")
file_to_delete.unlink(missing_ok=True) # Delete file safely
7. Deleting Directories
7.1 Remove an Empty Directory
dir_to_remove = Path("empty_folder")
dir_to_remove.rmdir() # Removes only if empty
7.2 Remove a Directory with Contents
import shutil
shutil.rmtree("folder_with_files") # Deletes folder and all contents
8. Getting File Information
8.1 File Name and Extension
file = Path("example.txt")
print(file.name) # example.txt
print(file.stem) # example (filename without extension)
print(file.suffix) # .txt (file extension)
8.2 Get File Size
print(file.stat().st_size, "bytes") # File size in bytes
8.3 Get File Creation and Modification Time
import datetime
mod_time = file.stat().st_mtime
print(datetime.datetime.fromtimestamp(mod_time)) # Convert to readable date
9. Path Manipulation
9.1 Get Parent Directory
file = Path("/home/user/documents/example.txt")
print(file.parent) # Output: /home/user/documents
9.2 Join Paths
new_path = Path("/home/user") / "documents" / "file.txt"
print(new_path) # Output: /home/user/documents/file.txt
9.3 Absolute Path
relative_path = Path("example.txt")
print(relative_path.resolve()) # Converts to absolute path
10. Summary Table
Feature | Method |
---|---|
Get Current Directory | Path.cwd() |
Get Home Directory | Path.home() |
Check if Exists | path.exists() |
Check if File | path.is_file() |
Check if Directory | path.is_dir() |
Create Directory | path.mkdir(parents=True, exist_ok=True) |
Create File | path.touch() |
List Files in Directory | path.iterdir() |
Find Files by Pattern | path.glob("*.txt") |
Read File | path.read_text() |
Write to File | path.write_text("Hello") |
Copy File | shutil.copy(source, destination) |
Move File | path.rename(new_path) |
Delete File | path.unlink(missing_ok=True) |
Delete Directory | shutil.rmtree(path) |
Get File Size | path.stat().st_size |
Get File Name | path.name |
Get File Extension | path.suffix |
Join Paths | path1 / "subdir" / "file.txt" |