File Handling - Reading and Writing Files

Files let you store data permanently (even after program ends). Three main modes: 'r' = read only, 'w' = write (creates new or overwrites), 'a' = append (adds to end). Always close files after using them, or use 'with' statement which closes automatically.

# File handling examples
import os

# Example 1: Writing to a file
print("Example 1: Writing to a file")

# Writing a new file
with open("diary.txt", "w") as file:
    file.write("My Daily Diary\n")
    file.write("==============\n\n")
    file.write("Today I learned Python file handling!\n")
    file.write("It's amazing how I can save data permanently.\n")

print("Created diary.txt file")

# Example 2: Reading from a file
print("\nExample 2: Reading the file")
print("Contents of diary.txt:")
print("-" * 30)

with open("diary.txt", "r") as file:
    content = file.read()
    print(content)

# Example 3: Reading line by line
print("\nExample 3: Reading line by line")
print("Each line separately:")

with open("diary.txt", "r") as file:
    lines = file.readlines()
    for i, line in enumerate(lines, 1):
        print(f"Line {i}: {line.strip()}")

# Example 4: Appending to a file
print("\nExample 4: Adding more to diary")

with open("diary.txt", "a") as file:
    file.write("\nTomorrow I'll learn about error handling!\n")
    file.write("I'm excited to continue learning Python.\n")

print("Appended new entries to diary.txt")

# Show updated content
print("\nUpdated diary:")
with open("diary.txt", "r") as file:
    print(file.read())

# Example 5: Working with CSV (Comma Separated Values)
print("\nExample 5: Creating a CSV file")

# Create a CSV file
with open("students.csv", "w") as file:
    file.write("Name,Age,Grade\n")
    file.write("Alice,20,A\n")
    file.write("Bob,21,B\n")
    file.write("Charlie,19,A\n")

print("Created students.csv file")

# Read and process CSV
print("\nStudent Records:")
with open("students.csv", "r") as file:
    for line in file:
        name, age, grade = line.strip().split(",")
        if name != "Name":  # Skip header
            print(f"Student: {name}, Age: {age}, Grade: {grade}")

# Example 6: File existence check
print("\nExample 6: Checking file information")

filename = "diary.txt"
if os.path.exists(filename):
    size = os.path.getsize(filename)
    print(f"File '{filename}' exists.")
    print(f"Size: {size} bytes")
    print(f"Path: {os.path.abspath(filename)}")
else:
    print(f"File '{filename}' does not exist.")

# Cleanup (optional)
# os.remove("diary.txt")
# os.remove("students.csv")