Day 2: Files, Errors & System Interaction
📋 Today's Agenda
View Topics
▶
| Topic |
|---|
| File Handling |
| Error Handling |
| OS and sys Modules |
| ☕ Break |
| Subprocess Module |
| Hands-On Practice |
📁 File Handling
Reading Files
# Read entire file
with open('config.txt', 'r') as file:
content = file.read()
print(content)
# Read line by line
with open('log.txt', 'r') as file:
for line in file:
print(line.strip())
# Read with encoding
with open('data.txt', 'r', encoding='utf-8') as file:
content = file.read()
# Check if file exists first
import os
if os.path.exists('config.txt'):
with open('config.txt', 'r') as file:
print(file.read())
Writing Files
# Write simple text
with open('backup.txt', 'w') as file:
file.write("Backup created\n")
# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open('data.txt', 'w') as file:
for line in lines:
file.write(line + '\n')
# Write with timestamp
import datetime
with open('log.txt', 'w') as file:
timestamp = datetime.datetime.now()
file.write(f"Created: {timestamp}\n")
Appending to Files
# Append new entry
with open('log.txt', 'a') as file:
file.write("New log entry\n")
# Append with timestamp
import datetime
with open('log.txt', 'a') as file:
timestamp = datetime.datetime.now()
file.write(f"[{timestamp}] User login\n")
# Log function with error handling
def log_event(message):
try:
with open('system.log', 'a') as file:
file.write(f"{message}\n")
except:
print("Could not write to log file")
🛡️ Error Handling
Try/Except Basics
# Simple try/except
try:
with open('file.txt', 'r') as file:
print(file.read())
except:
print("File not found")
# Specific error types
try:
with open('config.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
# Get error details
try:
result = 10 / 0
except Exception as e:
print(f"Error: {e}")
# Try/except with else (runs if no error)
try:
with open('data.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found")
else:
print("File read successfully")
# Try/except with finally (always runs)
try:
file = open('test.txt', 'r')
content = file.read()
except:
print("Error")
finally:
print("This always runs")
📝 Logging
# Basic logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Script started")
logging.warning("Warning message")
logging.error("Error message")
# Log to file
import logging
logging.basicConfig(filename='app.log', level=logging.INFO)
logging.info("Application started")
# Different log levels
logging.debug("Debug message") # Won't show (level is INFO)
logging.info("Info message") # Shows
logging.warning("Warning message") # Shows
logging.error("Error message") # Shows
# Log with timestamp
import logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logging.info("Event occurred")
🖥️ OS Module
import os # Get current directory print(os.getcwd())
# List files in directory
files = os.listdir('.')
for file in files:
print(file)
# Check if file exists
if os.path.exists('config.txt'):
print("File exists")
# Get file size
if os.path.exists('log.txt'):
size = os.path.getsize('log.txt')
print(f"File size: {size} bytes")
# Create directory
os.makedirs('backup', exist_ok=True)
🔧 SYS Module
import sys # Get Python version print(sys.version)
# Get command line arguments
print("Script:", sys.argv[0])
print("Arguments:", sys.argv[1:])
# Get platform
print("Platform:", sys.platform)
# Check Python path
for path in sys.path:
print(path)
🚀 Subprocess Module
Basic Subprocess
import subprocess # Run simple command result = subprocess.run(['echo', 'Hello'], capture_output=True, text=True) print(result.stdout)
# Run with arguments result = subprocess.run(['echo', 'test'], capture_output=True, text=True) print(result.stdout)
# Check return code
result = subprocess.run(['ls'], capture_output=True, text=True)
if result.returncode == 0:
print("Command successful")
else:
print("Command failed")
# Get both output and errors
result = subprocess.run(['ls', 'nonexistent'], capture_output=True, text=True)
print("Output:", result.stdout)
print("Errors:", result.stderr)
Safe Command Execution
import subprocess
def run_command(command):
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
return result.stdout
except:
return "Command failed"
# Example usage output = run_command(['echo', 'Hello from subprocess']) print(output)
🛠️ Hands-On: Log Parser
Simple log reader
def read_log(filename):
try:
with open(filename, 'r') as file:
for line in file:
print(line.strip())
except FileNotFoundError:
print("Log file not found")
# Count lines in log
def count_log_lines(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
except FileNotFoundError:
print("Log file not found")
# Find error lines
def find_errors(filename):
try:
with open(filename, 'r') as file:
for line in file:
if 'ERROR' in line:
print(line.strip())
except FileNotFoundError:
print("Log file not found")
# Create log summary
def log_summary(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
error_count = sum(1 for line in lines if 'ERROR' in line)
print(f"Error lines: {error_count}")
except FileNotFoundError:
print("Log file not found")
🛠️ Hands-On: Command Wrapper
import subprocess
def run_safe(command):
try:
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
return result.stdout
except:
return "Error running command"
# System info collector
def get_system_info():
info = {}
info['user'] = run_safe(['whoami']).strip()
info['directory'] = run_safe(['pwd']).strip()
return info
# Check disk space (Linux)
def check_disk():
try:
result = subprocess.run(['df', '-h'], capture_output=True, text=True)
return result.stdout
except:
return "Could not check disk space"
# List processes
def list_processes():
try:
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
return result.stdout
except:
return "Could not list processes"
✅ What We Did Today
- Read and wrote files
- Handled errors safely with try/except
- Used the logging module
- Explored os and sys modules
- Ran system commands with subprocess
- Created log parser and command wrapper scripts
🏠 Homework
- Create a script that reads a log file and counts errors
- Write a function that runs a system command safely
- Practice error handling with file operations