- Create, remove, and manipulate files and directories
- Use shutil for advanced file operations
- Manage file permissions and metadata
- Apply best practices for file system operations
File and Directory Management
Creating and Removing Files
Python provides tools to manage the file system programmatically, like a digital librarian organizing books and shelves.
Creating Files
# Create an empty file
with open('new_file.txt', 'w') as file:
pass # Just create the file
# Create file with initial content
with open('new_file.txt', 'w') as file:
file.write("Initial content")
Removing Files
import os
# Remove a file
os.remove('file_to_delete.txt')
# Safe removal with existence check
if os.path.exists('file_to_delete.txt'):
os.remove('file_to_delete.txt')
Directory Operations
Creating Directories
import os
# Create single directory
os.mkdir('new_directory')
# Create nested directories
os.makedirs('parent/child/grandchild')
Removing Directories
# Remove empty directory
os.rmdir('empty_directory')
# Remove directory tree (dangerous!)
import shutil
shutil.rmtree('directory_tree')
Renaming Files and Directories
# Rename file
os.rename('old_name.txt', 'new_name.txt')
# Rename directory
os.rename('old_dir', 'new_dir')
Copying Files and Directories
The shutil module provides high-level file operations.
import shutil
# Copy file
shutil.copy('source.txt', 'destination.txt')
# Copy file with metadata
shutil.copy2('source.txt', 'destination.txt')
# Copy directory tree
shutil.copytree('source_dir', 'destination_dir')
File Permissions
Checking Permissions
import os
# Check if file is readable
os.access('file.txt', os.R_OK)
# Check if writable
os.access('file.txt', os.W_OK)
# Check if executable
os.access('file.txt', os.X_OK)
Changing Permissions
# Change permissions (Unix-style)
os.chmod('file.txt', 0o755)
File Metadata
Getting File Information
import os
# File size
size = os.path.getsize('file.txt')
# Modification time
mtime = os.path.getmtime('file.txt')
# Convert to readable format
import time
readable_time = time.ctime(mtime)
File Properties
# Check if path is file
os.path.isfile('path')
# Check if path is directory
os.path.isdir('path')
# Get file extension
extension = os.path.splitext('file.txt')[1]
Temporary Files
import tempfile
# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
temp_file.write("Temporary content")
temp_path = temp_file.name
# Clean up
os.unlink(temp_path)
Organizing Project Structure Example
Building a file backup system:
- Create backup directories with timestamps
- Copy important files to backup location
- Compress backup folders
- Clean up old backups
- Log backup operations
Best Practices
- Always check file/directory existence before operations
- Use absolute paths when possible to avoid confusion
- Handle permission errors gracefully
- Be extremely careful with rmtree() - it deletes everything
- Use temporary files for intermediate operations
- Log file operations for debugging
Mastering file and directory management gives you complete control over your application's data storage and organization. It's like being the chief librarian of your digital world.
