Skip to main content

Python File Handling: Read, Write, and Process Files

Intermediate25 min5 exercises70 XP
0/5 exercises

Imagine you have a notebook where you write down important things. You open it, read what's inside, add new notes, and then close it. Python works with files the same way.

So far, all the data in your programs disappears the moment the program stops running. Variables only live in memory. Files let you save data permanently so it's still there tomorrow, next week, or next year.

In this tutorial, you'll learn how to open files, read their contents, write new data, and safely close them. We'll use Python's io.StringIO to simulate files right in your browser so you can practice everything interactively.

How Do You Open a File in Python?

The open() function is your gateway to working with files. It takes a filename and a mode that says what you want to do with the file.

Here are the most common modes:

  • 'r'Read (default). Opens the file for reading. The file must already exist.
  • 'w'Write. Creates a new file or erases an existing one, then lets you write.
  • 'a'Append. Opens a file and adds new content to the end without erasing anything.
  • 'x'Create. Creates a new file but fails if the file already exists.
  • Opening and reading a simulated file
    Loading editor...

    In a real program on your computer, you would write open('notes.txt', 'r') instead of io.StringIO(). The reading and writing methods work exactly the same way.

    What Are the Different Ways to Read a File?

    Python gives you three main ways to read from a file. Each one is useful in different situations, like choosing between reading an entire book at once, reading one page at a time, or getting a list of all pages.

    read() — Get Everything at Once

    The read() method returns the entire file as one big string. This is perfect for small files where you need all the content.

    read() returns the whole file as a string
    Loading editor...

    readline() — One Line at a Time

    The readline() method reads a single line, including the \n newline character at the end. Each call moves forward to the next line, like turning a page.

    readline() reads one line per call
    Loading editor...

    readlines() — All Lines as a List

    The readlines() method reads every line and returns them as a list of strings. Each string still includes the \n at the end.

    readlines() returns a list of lines
    Loading editor...
    Looping directly over a file object
    Loading editor...

    How Do You Write Data to a File?

    Writing to a file is like writing in your notebook. You use the write() method to add text. Unlike print(), the write() method does not add a newline automatically. You need to include \n yourself.

    Writing text to a file
    Loading editor...

    Notice the f.seek(0) call. After writing, the cursor is at the end of the file. seek(0) moves it back to the beginning so read() can see everything. Think of it like rewinding a tape.

    What Is the Difference Between Write and Append?

    In real file handling, write mode ('w') erases the file first, then writes. Append mode ('a') keeps the existing content and adds new text at the end.

    Write mode ('w') — erases first
    # On a real system:
    # f = open('log.txt', 'w')
    # f.write('New data\n')
    # Existing content is gone!
    Append mode ('a') — keeps existing
    # On a real system:
    # f = open('log.txt', 'a')
    # f.write('New data\n')
    # Old content is preserved!

    Why Should You Use the with Statement for Files?

    Every time you open a file, you should close it when you're done. Forgetting to close a file can cause data loss or lock the file so other programs can't use it.

    The with statement handles closing automatically. When the indented block ends, Python closes the file for you, even if an error occurs. This is the recommended way to work with files.

    The with statement closes files automatically
    Loading editor...

    What Are All the File Modes in Python?

    Here is a complete reference of the most useful file modes:
    -------------------
    'r'Read (default). File must exist.
    'w'Write. Creates or erases the file.
    'a'Append. Adds to the end.
    'x'Create. Fails if file exists.
    'rb'Read binary (images, PDFs).
    'wb'Write binary.

    You can also combine modes. Adding '+' makes a mode do both reading and writing. For example, 'r+' opens an existing file for both reading and writing.

    What Are Common File Handling Patterns?

    Let's look at a few patterns you'll use all the time when working with files.

    Reading a file into a list of clean lines

    Clean lines with list comprehension
    Loading editor...

    Writing a list to a file

    Writing a list of items to a file
    Loading editor...

    Counting lines in a file

    Count lines efficiently
    Loading editor...

    Practice Exercises

    Read and Print File Contents
    Write Code

    You are given a simulated file f containing three fruit names, one per line. Read all lines from the file using a for loop and print each fruit name without any trailing whitespace or newlines.

    The file contains:

    apple
    banana
    cherry

    Print each fruit on its own line.

    Loading editor...
    Predict the Read Output
    Predict Output

    What does this code print? Think about what readlines() returns and how len() works on a list.

    import io
    
    f = io.StringIO('a\nb\nc\nd\n')
    lines = f.readlines()
    print(len(lines))
    f.close()
    Loading editor...
    Write and Read Back
    Write Code

    Create a StringIO object, write three lines to it ('Python\n', 'Java\n', 'JavaScript\n'), then seek back to the start and read all the content. Print the content using print(content, end='') to avoid an extra blank line.

    Loading editor...
    Fix the File Reading Bug
    Fix the Bug

    This code tries to read a file twice, but the second read returns an empty string. Fix the bug so both reads print the file content.

    Expected output:

    First read: hello
    Second read: hello
    Loading editor...
    Line Number Formatter
    Write Code

    Write a function called add_line_numbers(text) that takes a multi-line string and returns a new string where each line is prefixed with its line number and a colon.

    For example, given 'apple\nbanana\ncherry', the function should return '1: apple\n2: banana\n3: cherry'.

    After defining the function, call it with the test string and print the result using print(result, end='') to avoid trailing newlines.

    Loading editor...