Skip to content

APPEND MODE - Adding content to existing files

Python
#!/usr/bin/env python3
"""
APPEND MODE - Adding content to existing files
Demonstrates how to add content without overwriting
"""

import os
import tempfile

print("=" * 60)
print("APPEND MODE - Adding to Existing Files")
print("=" * 60)

temp_dir = tempfile.gettempdir()
log_file = os.path.join(temp_dir, "application.log")

# Example 1: Create initial file
print("\n1. Creating Initial Log File")
print("-" * 40)
f = open(log_file, 'w')
f.write("2024-01-01 10:00:00 - Application started\n")
f.write("2024-01-01 10:00:05 - User logged in\n")
f.close()

f = open(log_file, 'r')
print("Initial content:")
print(f.read())
f.close()

# Example 2: Append new entries
print("\n2. Appending New Log Entries")
print("-" * 40)
f = open(log_file, 'a')
f.write("2024-01-01 10:05:00 - Data saved\n")
f.write("2024-01-01 10:10:00 - Report generated\n")
f.close()

f = open(log_file, 'r')
print("After appending:")
print(f.read())
f.close()

# Example 3: Multiple append operations
print("\n3. Multiple Append Operations")
print("-" * 40)
events = [
    "2024-01-01 10:15:00 - Email sent\n",
    "2024-01-01 10:20:00 - Backup completed\n",
    "2024-01-01 10:25:00 - User logged out\n"
]

for event in events:
    f = open(log_file, 'a')
    f.write(event)
    f.close()
    print(f"Appended: {event.strip()}")

f = open(log_file, 'r')
print("\nFinal log file:")
print(f.read())
f.close()

# Example 4: Append mode creates file if not exists
print("\n4. Append Mode Creates File If Not Exists")
print("-" * 40)
new_file = os.path.join(temp_dir, "new_log.txt")

# This won't fail even though file doesn't exist
f = open(new_file, 'a')
f.write("First line in new file\n")
f.close()

f = open(new_file, 'r')
print(f"Created {new_file}:")
print(f.read())
f.close()

# Example 5: Building a report incrementally
print("\n5. Building a Report Incrementally")
print("-" * 40)
report_file = os.path.join(temp_dir, "sales_report.txt")

# Header
f = open(report_file, 'w')
f.write("DAILY SALES REPORT\n")
f.write("=" * 40 + "\n")
f.close()

# Add sales data incrementally
sales_data = [
    ("Product A", 150),
    ("Product B", 200),
    ("Product C", 175),
]

for product, amount in sales_data:
    f = open(report_file, 'a')
    f.write(f"{product}: ${amount}\n")
    f.close()

# Footer
f = open(report_file, 'a')
f.write("=" * 40 + "\n")
total = sum(amount for _, amount in sales_data)
f.write(f"Total: ${total}\n")
f.close()

f = open(report_file, 'r')
print("Final report:")
print(f.read())
f.close()

# Cleanup
for f in [log_file, new_file, report_file]:
    if os.path.exists(f):
        os.remove(f)

print("\n" + "=" * 60)
print("Key Points:")
print("  - Mode 'a' appends to end of file")
print("  - Doesn't overwrite existing content")
print("  - Creates file if it doesn't exist")
print("  - Perfect for logs and incremental data")
print("=" * 60)