Practical Applications
File and Directory Management with os
Module
import os
## Get current working directory
current_dir = os.getcwd()
print(f"Current Directory: {current_dir}")
## List directory contents
print("Directory Contents:")
print(os.listdir())
## Create and remove directories
os.mkdir('example_folder')
os.rmdir('example_folder')
Data Processing with json
Module
import json
## Parsing JSON data
data = '{"name": "LabEx", "version": 3.0}'
parsed_data = json.loads(data)
print(parsed_data['name'])
## Writing JSON file
user_info = {
'username': 'developer',
'skills': ['Python', 'Data Science']
}
with open('user.json', 'w') as f:
json.dump(user_info, f)
Date and Time Manipulation
from datetime import datetime, timedelta
## Current timestamp
current_time = datetime.now()
print(f"Current Time: {current_time}")
## Date calculations
future_date = current_time + timedelta(days=30)
print(f"30 Days from Now: {future_date}")
System Interaction with sys
Module
import sys
## System information
print(f"Python Version: {sys.version}")
print(f"Platform: {sys.platform}")
## Command-line arguments
print("Script Arguments:", sys.argv)
Regular Expression Processing
import re
## Pattern matching
text = "Contact LabEx at [email protected]"
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
matches = re.findall(email_pattern, text)
print("Extracted Emails:", matches)
Module Application Scenarios
Module |
Primary Use Case |
Key Functions |
os |
System Operations |
Path manipulation, directory management |
json |
Data Serialization |
Parse/generate JSON data |
datetime |
Time Handling |
Date calculations, formatting |
sys |
System Interaction |
Access system-specific parameters |
re |
Text Processing |
Pattern matching, string manipulation |
Advanced Module Interactions
graph TD
A[Python Standard Modules] --> B[System Interaction]
A --> C[Data Processing]
A --> D[Network Operations]
B --> E[os, sys]
C --> F[json, csv]
D --> G[urllib, socket]
- Import modules only when needed
- Use specific imports to reduce memory overhead
- Leverage built-in functions for efficiency
LabEx Recommended Workflow
- Understand module purpose
- Explore module documentation
- Practice with practical examples
- Integrate modules in real projects
By mastering these practical applications, you'll enhance your Python programming capabilities and solve complex problems efficiently.