Python Programming Labs

Master essential Python modules: JSON serialization, pathlib for file paths, and datetime for time handling.

Data & File Handling Essentials - Module 9

Work with JSON data, file paths, and dates/times like a professional.

Lab 25: JSON & Serialization
Expert
Coding Challenge
Your Task: Learn to serialize and deserialize data using Python's json module for data interchange.

Detailed Requirements:
1. Basic JSON operations:
import json # Python dict to JSON string data = {"name": "Alice", "age": 30, "active": True} json_string = json.dumps(data) print(json_string) # '{"name": "Alice", "age": 30, "active": true}' # JSON string to Python dict parsed = json.loads(json_string) print(parsed["name"]) # Alice

2. Pretty printing and formatting:
# Pretty print with indentation data = {"users": [{"name": "Alice"}, {"name": "Bob"}]} pretty = json.dumps(data, indent=2, sort_keys=True) print(pretty) # Custom separators compact = json.dumps(data, separators=(',', ':')) print(compact) # No extra spaces

3. File operations:
# Write JSON to file with open('data.json', 'w') as f: json.dump(data, f, indent=2) # Read JSON from file with open('data.json', 'r') as f: loaded = json.load(f) print(loaded)

4. Custom serialization:
from datetime import datetime class DateEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() return super().default(obj) data = {"timestamp": datetime.now()} json_str = json.dumps(data, cls=DateEncoder) print(json_str) # {"timestamp": "2024-01-15T10:30:00"}

💡 Pro Tips:
• dumps/loads work with strings
• dump/load work with files
• Use indent for human-readable output
• Custom encoder for non-JSON types

Expected Output:
JSON: {"name": "Alice", "age": 30} Parsed: {'name': 'Alice', 'age': 30} Pretty printed JSON with indentation

Requirements Checklist

Import json module
Use json.dumps() to serialize
Use json.loads() to deserialize
Use indent parameter for pretty printing
Use json.dump() or json.load() for files
Print results to verify
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: import json
• Serialize: json.dumps(data) → string
• Deserialize: json.loads(string) → dict
• Pretty: json.dumps(data, indent=2)
• Files: json.dump() / json.load()
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 26: Pathlib Module
Expert
Coding Challenge
Your Task: Master the pathlib module for modern, object-oriented file path handling.

Detailed Requirements:
1. Creating and using paths:
from pathlib import Path # Create path objects home = Path.home() current = Path.cwd() file_path = Path('/usr/local/bin/python') # Path from string p = Path('folder/subfolder/file.txt') print(p) # folder/subfolder/file.txt

2. Path components:
p = Path('/home/user/documents/report.pdf') print(p.name) # report.pdf print(p.stem) # report print(p.suffix) # .pdf print(p.parent) # /home/user/documents print(p.parts) # ('/', 'home', 'user', 'documents', 'report.pdf') print(p.anchor) # /

3. Path operations:
# Joining paths (use / operator) base = Path('/home/user') full = base / 'documents' / 'file.txt' print(full) # /home/user/documents/file.txt # Changing extensions p = Path('data.csv') new_p = p.with_suffix('.json') print(new_p) # data.json # Changing filename p = Path('folder/old.txt') new_p = p.with_name('new.txt') print(new_p) # folder/new.txt

4. File system operations:
p = Path('myfile.txt') # Check existence print(p.exists()) # True/False print(p.is_file()) # True if file print(p.is_dir()) # True if directory # List directory contents folder = Path('.') for item in folder.iterdir(): print(item) # Glob patterns for py_file in folder.glob('*.py'): print(py_file) # Recursive glob for py_file in folder.rglob('**/*.py'): print(py_file)

💡 Pro Tips:
• Use / operator to join paths
• Path.cwd() for current directory
• Path.home() for home directory
• glob() and rglob() for pattern matching

Expected Output:
Path: /home/user/documents/file.txt Name: file.txt Stem: file Suffix: .txt

Requirements Checklist

Import Path from pathlib
Create Path objects
Access path components (name, stem, suffix)
Join paths using / operator
Use glob or iterdir for listing
Print results to verify
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: from pathlib import Path
• Create: p = Path('folder/file.txt')
• Components: p.name, p.stem, p.suffix
• Join: base / 'subdir' / 'file.txt'
• Find: Path('.').glob('*.py')
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 27: Datetime Module
Expert
Coding Challenge
Your Task: Master the datetime module for working with dates, times, and time deltas.

Detailed Requirements:
1. Current date and time:
from datetime import datetime, date, time, timedelta # Current datetime now = datetime.now() print(now) # 2024-01-15 10:30:45.123456 # Current date only today = date.today() print(today) # 2024-01-15 # UTC time utc_now = datetime.utcnow() print(utc_now)

2. Creating specific dates/times:
# Create specific datetime dt = datetime(2024, 12, 25, 14, 30, 0) print(dt) # 2024-12-25 14:30:00 # Create date d = date(2024, 7, 4) print(d) # 2024-07-04 # Create time t = time(14, 30, 45) print(t) # 14:30:45

3. Formatting and parsing:
# Format datetime to string now = datetime.now() formatted = now.strftime('%Y-%m-%d %H:%M:%S') print(formatted) # 2024-01-15 10:30:45 # Common format codes: # %Y - Year (2024) %m - Month (01-12) # %d - Day (01-31) %H - Hour (00-23) # %M - Minute (00-59) %S - Second (00-59) # %A - Weekday name %B - Month name # Parse string to datetime date_str = '2024-12-25' parsed = datetime.strptime(date_str, '%Y-%m-%d') print(parsed) # 2024-12-25 00:00:00

4. Time arithmetic with timedelta:
# Create time deltas one_day = timedelta(days=1) one_week = timedelta(weeks=1) custom = timedelta(days=5, hours=3, minutes=30) # Add/subtract from dates now = datetime.now() tomorrow = now + one_day yesterday = now - one_day next_week = now + one_week print(f"Tomorrow: {tomorrow}") print(f"Yesterday: {yesterday}") # Difference between dates d1 = datetime(2024, 1, 1) d2 = datetime(2024, 12, 31) diff = d2 - d1 print(f"Days between: {diff.days}")

💡 Pro Tips:
• strftime = string from time (format)
• strptime = string parse time (parse)
• Use timedelta for date math
• date.today() for just the date

Expected Output:
Now: 2024-01-15 10:30:45 Formatted: January 15, 2024 Tomorrow: 2024-01-16 10:30:45

Requirements Checklist

Import from datetime module
Get current date/time with now() or today()
Create specific datetime objects
Format with strftime()
Use timedelta for date arithmetic
Print results to verify
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: from datetime import datetime, date, timedelta
• Now: datetime.now() or date.today()
• Create: datetime(2024, 12, 25, 14, 30)
• Format: dt.strftime('%Y-%m-%d')
• Math: now + timedelta(days=7)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below