Lesson 4 • Intermediate

    File Handling in Python

    Learn to read, write, and manage files to save data permanently.

    What You'll Learn in This Lesson

    • Why files are essential for saving data permanently
    • File modes: read (r), write (w), append (a), create (x)
    • How to safely open files using the with statement
    • How to read entire files, line by line, or as a list
    • How to write and append to files
    • How to check if a file exists and work with CSV/JSON

    1. Why Learn File Handling?

    When your program ends, all variables are lost. Files let you save data permanently so it survives after your program closes.

    What Can You Do with Files?

    • Save user data — Store settings, preferences, scores
    • Read data — Load configuration, import information
    • Create logs — Track events and errors
    • Process data — Work with CSV, JSON, or text files

    2. Opening Files with open()

    Use the open() function to work with files. You specify the filename and a mode that tells Python what you want to do.

    # Syntax
    file = open("filename.txt", "mode")
    ModeNameWhat It Does
    "r"ReadOpen for reading (file must exist)
    "w"WriteCreate new or overwrite existing
    "a"AppendAdd to end (keeps existing content)
    "x"CreateCreate new (error if file exists)

    3. The with Statement (Best Practice)

    Always use the with statement when working with files. It automatically closes the file when you are done, even if an error occurs.

    Without with (risky)
    file = open("data.txt", "r")
    content = file.read()
    file.close()  # Easy to forget!
    With with (safe)
    with open("data.txt", "r") as file:
        content = file.read()
    # Automatically closed!

    4. Reading Files

    There are several ways to read file content:

    MethodWhat It ReturnsBest For
    .read()Entire file as one stringSmall files
    .readline()One line at a timeProcessing line by line
    .readlines()List of all linesWhen you need a list
    for line in file:Each line (loop)Large files (memory efficient)

    Try It: Reading Files

    Different ways to read file content

    Try it Yourself »
    Python
    # Simulating file reading (since we can't create real files here)
    file_content = """Line 1: Hello Python!
    Line 2: File handling is useful.
    Line 3: Keep practicing!"""
    
    # Simulate .read() - entire file
    print("=== read() - Entire file ===")
    print(file_content)
    
    # Simulate .readlines() - list of lines
    print("\n=== readlines() - List of lines ===")
    lines = file_content.split("\n")
    print(lines)
    
    # Simulate looping through lines
    print("\n=== Loop through lines ===")
    for i, line in enumerate(lines, 1):
    ...

    5. Writing to Files

    Use mode "w" to write to a file. This creates a new file or overwrites an existing one.

    # Writing to a file
    with open("output.txt", "w") as file:
    file.write("Hello, World!\\n")
    file.write("Second line\\n")

    Try It: Writing Files

    Save data to a file

    Try it Yourself »
    Python
    # Simulating file writing
    output = []
    
    # Simulate writing lines
    output.append("Hello, World!")
    output.append("This is line 2.")
    output.append("Python file handling is easy!")
    
    print("=== File would contain ===")
    for line in output:
        print(line)
    
    # Real code would be:
    # with open("output.txt", "w") as file:
    #     file.write("Hello, World!\n")
    #     file.write("This is line 2.\n")

    6. Appending to Files

    Use mode "a" to add content to the end of a file without deleting existing content.

    # Appending to a file
    with open("log.txt", "a") as file:
    file.write("New log entry\\n")

    Try It: Appending

    Add to files without overwriting

    Try it Yourself »
    Python
    # Simulating append behavior
    existing_content = [
        "Log entry 1: Started app",
        "Log entry 2: User logged in"
    ]
    
    print("=== Existing content ===")
    for line in existing_content:
        print(line)
    
    # Append new entries
    existing_content.append("Log entry 3: New action performed")
    existing_content.append("Log entry 4: User logged out")
    
    print("\n=== After appending ===")
    for line in existing_content:
        print(line)
    ModeExisting ContentUse Case
    "w"Deleted (overwritten)Creating new files, saving fresh data
    "a"Kept (added to)Logs, history, collecting data

    7. Checking if a File Exists

    Before reading a file, check if it exists to avoid errors:

    Try It: Check File Exists

    Verify file exists before opening

    Try it Yourself »
    Python
    import os
    
    # Check if file exists
    filename = "data.txt"
    
    # Simulating os.path.exists behavior
    files_on_disk = ["notes.txt", "config.json", "data.txt"]
    
    if filename in files_on_disk:
        print(f"'{filename}' exists! Safe to open.")
    else:
        print(f"'{filename}' not found.")
    
    # Real code:
    # if os.path.exists("data.txt"):
    #     with open("data.txt", "r") as file:
    #         content = file.read()
    # else:
    #     print("File not found")

    8. Handling File Errors

    Use try-except to handle errors gracefully when working with files:

    ErrorCause
    FileNotFoundErrorFile does not exist (reading mode)
    PermissionErrorNo permission to access file
    IsADirectoryErrorTried to open a folder as a file

    Try It: Error Handling

    Handle file errors gracefully

    Try it Yourself »
    Python
    # Safe file reading with try-except
    
    def read_file_safely(filename):
        try:
            # Simulate file operations
            if filename == "missing.txt":
                raise FileNotFoundError(f"No such file: '{filename}'")
            elif filename == "protected.txt":
                raise PermissionError(f"Access denied: '{filename}'")
            else:
                return f"Content of {filename}: Hello World!"
        except FileNotFoundError:
            return "Error: File not found."
        except PermissionError:
        
    ...

    9. Working with CSV Files

    CSV (Comma-Separated Values) is a common format for spreadsheet data. Python has a built-in csv module to work with it.

    Try It: CSV Files

    Read and write spreadsheet data

    Try it Yourself »
    Python
    import csv
    from io import StringIO
    
    # Create CSV data in memory
    csv_data = StringIO()
    writer = csv.writer(csv_data)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "London"])
    writer.writerow(["Bob", 30, "Paris"])
    writer.writerow(["Charlie", 35, "Tokyo"])
    
    # Read the CSV data
    csv_data.seek(0)
    print("=== CSV Content ===")
    reader = csv.reader(csv_data)
    for row in reader:
        print(row)
    
    # Using DictReader for easier access
    csv_data.seek(0)
    print("\n=== As Dictionaries ===")
    d
    ...

    10. Working with JSON Files

    JSON (JavaScript Object Notation) is used for configuration files and APIs. Python can easily convert between JSON and dictionaries.

    FunctionWhat It Does
    json.dumps(obj)Convert Python dict → JSON string
    json.loads(str)Convert JSON string → Python dict
    json.dump(obj, file)Write dict to JSON file
    json.load(file)Read JSON file to dict

    Try It: JSON Files

    Work with JSON data

    Try it Yourself »
    Python
    import json
    
    # Python dictionary
    data = {
        "name": "Alice",
        "age": 25,
        "skills": ["Python", "JavaScript"],
        "active": True
    }
    
    # Convert to JSON string (for saving to file)
    json_string = json.dumps(data, indent=2)
    print("=== JSON String ===")
    print(json_string)
    
    # Convert back to Python dict (for reading from file)
    parsed = json.loads(json_string)
    print("\n=== Back to Python ===")
    print(f"Name: {parsed['name']}")
    print(f"Skills: {parsed['skills']}")

    11. Common Mistakes to Avoid

    MistakeProblemSolution
    Forgetting to close fileData may not save, file lockedUse with statement
    Using "w" instead of "a"Existing data deletedDouble-check your mode
    Forgetting \nAll text on one lineAdd \n after each line
    Reading non-existent fileFileNotFoundErrorCheck with os.path.exists()
    Wrong encodingStrange characters appearAdd encoding="utf-8"

    12. Practical Examples

    Example 1: Simple Note Saver

    Note Saver

    Save notes to a file

    Try it Yourself »
    Python
    # Simple note saver simulation
    notes = []
    
    def save_note(note):
        notes.append(note)
        print(f"Saved: {note}")
    
    def show_notes():
        print("\n=== Your Notes ===")
        for i, note in enumerate(notes, 1):
            print(f"{i}. {note}")
    
    # Add some notes
    save_note("Buy groceries")
    save_note("Call mom")
    save_note("Finish Python lesson")
    
    # Display all notes
    show_notes()
    
    # Real implementation:
    # with open("notes.txt", "a") as f:
    #     f.write(note + "\n")

    Example 2: Word Counter

    Word Counter

    Analyze text content

    Try it Yourself »
    Python
    # Count words, lines, and characters in text
    
    text = """Python is a great programming language.
    It is easy to learn and very powerful.
    Many developers love using Python for various projects."""
    
    lines = text.split("\n")
    words = text.split()
    chars = len(text)
    
    print("=== Text Analysis ===")
    print(f"Lines: {len(lines)}")
    print(f"Words: {len(words)}")
    print(f"Characters: {chars}")
    
    # Count word frequency
    word_count = {}
    for word in words:
        word = word.lower().strip(".,!?")
        word_count[word] =
    ...

    Example 3: Simple Log System

    Log System

    Create activity logs with timestamps

    Try it Yourself »
    Python
    from datetime import datetime
    
    # Simple logging system
    log = []
    
    def log_event(event):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        entry = f"[{timestamp}] {event}"
        log.append(entry)
        print(entry)
    
    # Log some events
    log_event("Application started")
    log_event("User logged in")
    log_event("File saved successfully")
    log_event("User logged out")
    
    print("\n=== Complete Log ===")
    for entry in log:
        print(entry)

    Summary: Quick Reference

    OperationCode
    Read entire filewith open("f.txt", "r") as f: text = f.read()
    Read linesfor line in file:
    Write (overwrite)with open("f.txt", "w") as f: f.write("text")
    Appendwith open("f.txt", "a") as f: f.write("more")
    Check existsos.path.exists("f.txt")
    Read CSVcsv.reader(file)
    Read JSONjson.load(file)
    Write JSONjson.dump(data, file)
    🎉

    Lesson 9 complete — your programs can now save and load data!

    Reading, writing, appending, CSV, JSON — you know how to work with files safely using the with statement. Your programs can now remember things between runs.

    🚀 Up next: Exception Handling — learn to catch errors gracefully so your programs never crash unexpectedly.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service