This page shows the source code for Session-3-5-Examples.py in browser-friendly HTML format. It was generated automatically from the original Python file.
"""
Session 5: File Handling & Data Analysis - Code Examples
Introduction to Python Course
"""
import csv
from datetime import datetime
from collections import Counter
# ============================================
# PART 1: Reading Text Files
# ============================================
print("=" * 50)
print("PART 1: Reading Text Files")
print("=" * 50)
# Example 1: Create a sample text file
print("\n--- Example 1: Creating a Sample File ---")
sample_text = """Python is a powerful programming language.
It is easy to learn and versatile.
Python is used in web development, data science, and AI.
This is a sample text file for demonstration."""
with open("sample.txt", "w") as file:
file.write(sample_text)
print("✓ Created sample.txt")
# Example 2: Read entire file
print("\n--- Example 2: Reading Entire File ---")
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# Example 3: Read line by line
print("\n--- Example 3: Reading Line by Line ---")
with open("sample.txt", "r") as file:
for line_num, line in enumerate(file, 1):
print(f"Line {line_num}: {line.strip()}")
# Example 4: Read lines into list
print("\n--- Example 4: Reading Lines into List ---")
with open("sample.txt", "r") as file:
lines = file.readlines()
print(f"Total lines: {len(lines)}")
print(f"First line: {lines[0].strip()}")
# Example 5: Error handling
print("\n--- Example 5: Error Handling ---")
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("✗ Error: File not found!")
print("✓ Error handled gracefully")
# ============================================
# PART 2: Writing to Files
# ============================================
print("\n" + "=" * 50)
print("PART 2: Writing to Files")
print("=" * 50)
# Example 6: Writing to file
print("\n--- Example 6: Writing to File ---")
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is line 2.\n")
file.write("This is line 3.\n")
print("✓ Created output.txt")
# Example 7: Appending to file
print("\n--- Example 7: Appending to File ---")
with open("output.txt", "a") as file:
file.write("This line is appended.\n")
print("✓ Appended to output.txt")
# Read back to verify
with open("output.txt", "r") as file:
print("Contents of output.txt:")
print(file.read())
# Example 8: Writing multiple lines
print("\n--- Example 8: Writing Multiple Lines ---")
lines = [
"First line\n",
"Second line\n",
"Third line\n"
]
with open("multiline.txt", "w") as file:
file.writelines(lines)
print("✓ Created multiline.txt")
# ============================================
# PART 3: Working with CSV Files
# ============================================
print("\n" + "=" * 50)
print("PART 3: Working with CSV Files")
print("=" * 50)
# Example 9: Create sample CSV
print("\n--- Example 9: Creating Sample CSV ---")
employees = [
["name", "age", "city", "salary"],
["Alice", "25", "New York", "75000"],
["Bob", "30", "San Francisco", "85000"],
["Charlie", "28", "Boston", "72000"],
["Diana", "35", "Chicago", "90000"]
]
with open("employees.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(employees)
print("✓ Created employees.csv")
# Example 10: Reading CSV as dictionaries
print("\n--- Example 10: Reading CSV as Dictionaries ---")
with open("employees.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['name']:10} | Age: {row['age']:2} | {row['city']:15} | ${row['salary']}")
# Example 11: Reading CSV as lists
print("\n--- Example 11: Reading CSV as Lists ---")
with open("employees.csv", "r") as file:
reader = csv.reader(file)
header = next(reader)
print(f"Header: {header}")
for row in reader:
print(f"Row: {row}")
# Example 12: Writing dictionaries to CSV
print("\n--- Example 12: Writing Dictionaries to CSV ---")
products = [
{"product": "Laptop", "price": 999.99, "stock": 15},
{"product": "Mouse", "price": 25.50, "stock": 50},
{"product": "Keyboard", "price": 75.00, "stock": 30}
]
with open("products.csv", "w", newline='') as file:
fieldnames = ["product", "price", "stock"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(products)
print("✓ Created products.csv")
# ============================================
# PART 4: Data Analysis Example
# ============================================
print("\n" + "=" * 50)
print("PART 4: Data Analysis - Sales Data")
print("=" * 50)
# Example 13: Analyze sales data
print("\n--- Example 13: Sales Data Analysis ---")
# First, let's verify the sales.csv file exists
try:
with open("sales.csv", "r") as file:
reader = csv.DictReader(file)
sales = list(reader)
print(f"✓ Loaded {len(sales)} sales records\n")
# Calculate total revenue
total_revenue = sum(float(sale['amount']) for sale in sales)
print(f"Total Revenue: ${total_revenue:,.2f}")
# Find best selling product
products = [sale['product'] for sale in sales]
product_counts = Counter(products)
best_seller = product_counts.most_common(1)[0]
print(f"Best Seller: {best_seller[0]} ({best_seller[1]} sales)")
# Average sale amount
avg_sale = total_revenue / len(sales)
print(f"Average Sale: ${avg_sale:.2f}")
# Sales by category
print("\nRevenue by Category:")
categories = {}
for sale in sales:
category = sale['category']
amount = float(sale['amount'])
categories[category] = categories.get(category, 0) + amount
for category, total in sorted(categories.items()):
print(f" {category:15} : ${total:>10,.2f}")
# Find high-value sales (over $100)
high_value_sales = [
sale for sale in sales
if float(sale['amount']) > 100
]
print(f"\nHigh-value sales (>$100): {len(high_value_sales)}")
# Generate sales report
print("\n--- Generating Sales Report ---")
with open("sales_report.txt", "w") as file:
file.write("SALES ANALYSIS REPORT\n")
file.write("=" * 50 + "\n\n")
file.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
file.write(f"Total Sales: {len(sales)}\n")
file.write(f"Total Revenue: ${total_revenue:,.2f}\n")
file.write(f"Average Sale: ${avg_sale:.2f}\n")
file.write(f"\nBest Selling Product: {best_seller[0]} ({best_seller[1]} units)\n")
file.write("\nRevenue by Category:\n")
for category, total in sorted(categories.items()):
file.write(f" {category:15} : ${total:>10,.2f}\n")
file.write(f"\nHigh-value Sales: {len(high_value_sales)}\n")
print("✓ Created sales_report.txt")
except FileNotFoundError:
print("✗ sales.csv not found. Please ensure the file exists.")
print(" Creating sample sales data...")
# Create sample sales data
sample_sales = [
["date", "product", "category", "amount", "quantity"],
["2024-01-15", "Laptop", "Electronics", "1299.99", "1"],
["2024-01-15", "Mouse", "Electronics", "29.99", "2"],
["2024-01-16", "Desk", "Furniture", "399.99", "1"],
["2024-01-16", "Chair", "Furniture", "199.99", "2"],
["2024-01-17", "Laptop", "Electronics", "1299.99", "1"],
["2024-01-17", "Monitor", "Electronics", "249.99", "1"],
["2024-01-18", "Notebook", "Stationery", "5.99", "5"],
["2024-01-18", "Pen", "Stationery", "1.99", "10"]
]
with open("sales.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(sample_sales)
print("✓ Created sample sales.csv")
# ============================================
# PART 5: Practical Examples
# ============================================
print("\n" + "=" * 50)
print("PART 5: Practical Examples")
print("=" * 50)
# Example 14: Word frequency counter
print("\n--- Example 14: Word Frequency Counter ---")
with open("sample.txt", "r") as file:
text = file.read().lower()
# Remove punctuation and split into words
words = text.replace('.', '').replace(',', '').split()
word_count = Counter(words)
print("Top 5 most common words:")
for word, count in word_count.most_common(5):
print(f" {word:15} : {count} times")
# Example 15: Simple log analyzer
print("\n--- Example 15: Log Analyzer ---")
log_entries = [
"2024-01-15 10:30:00 INFO Application started\n",
"2024-01-15 10:30:15 WARNING Low memory detected\n",
"2024-01-15 10:30:30 ERROR Failed to connect to database\n",
"2024-01-15 10:30:45 INFO Connection retry successful\n",
"2024-01-15 10:31:00 ERROR Timeout occurred\n",
]
with open("application.log", "w") as file:
file.writelines(log_entries)
# Analyze log file
log_stats = {"INFO": 0, "WARNING": 0, "ERROR": 0}
with open("application.log", "r") as file:
for line in file:
for level in log_stats.keys():
if level in line:
log_stats[level] += 1
print("Log Analysis:")
for level, count in log_stats.items():
print(f" {level:10} : {count} occurrences")
# Example 16: Data filtering and exporting
print("\n--- Example 16: Data Filtering ---")
with open("employees.csv", "r") as file:
reader = csv.DictReader(file)
employees_list = list(reader)
# Filter high earners
high_earners = [
emp for emp in employees_list
if int(emp['salary']) > 75000
]
# Export filtered data
with open("high_earners.csv", "w", newline='') as file:
if high_earners:
fieldnames = high_earners[0].keys()
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(high_earners)
print(f"✓ Found {len(high_earners)} high earners (salary > $75,000)")
print("✓ Created high_earners.csv")
# ============================================
# Summary
# ============================================
print("\n" + "=" * 50)
print("SESSION 5 COMPLETE!")
print("=" * 50)
print("\nFiles created:")
print(" ✓ sample.txt - Sample text file")
print(" ✓ output.txt - Output file")
print(" ✓ multiline.txt - Multiple lines")
print(" ✓ employees.csv - Employee data")
print(" ✓ products.csv - Product inventory")
print(" ✓ sales.csv - Sales transactions")
print(" ✓ sales_report.txt - Analysis report")
print(" ✓ application.log - Sample log file")
print(" ✓ high_earners.csv - Filtered employee data")
print("\nYou now know how to:")
print(" • Read and write text files")
print(" • Work with CSV files")
print(" • Analyze data from files")
print(" • Generate reports")
print(" • Handle file errors")
print("\n🎉 Great job completing Session 5!")