Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python File Handling

Reading from and writing to files lets a Python program persist data beyond a single run, or process data that already exists on disk. Python's built-in open() function is the entry point for all file operations, returning a file object that supports reading, writing, and iteration.

The recommended way to work with files in Python is the with statement, which guarantees the file is properly closed as soon as the block finishes — even if an error occurs partway through — without requiring you to remember to call close() manually.

Why it matters

Programs keep data between runs by writing it to files: reports, exports, configuration, logs. The rules are few, but mistakes are costly: opening a file in the wrong mode erases it, and forgetting to close it can lose data. The with statement shown in this lesson is the form used in all professional code.

Opening Files and Modes

open(filename, mode) opens a file and returns a file object. The mode string controls how the file is accessed.

  • "r" — read (default); the file must already exist, or a FileNotFoundError is raised.
  • "w" — write; creates the file if it does not exist, and completely overwrites (truncates) it if it does.
  • "a" — append; creates the file if it does not exist, and adds new content to the end without erasing what is already there.
  • "r+" — read and write, without truncating the existing content.
  • Adding "b" to any mode (e.g. "rb", "wb") opens the file in binary mode instead of text mode.

The with Statement (Context Manager)

Writing with open("data.txt", "r") as f: opens the file and binds it to the name f for the duration of the indented block. When the block ends — normally or due to an exception — Python automatically calls f.close() for you. This pattern is strongly preferred over manually calling open() and close(), because a forgotten close() can leave a file locked or its buffered writes unflushed.

Reading and Writing Content

Inside a "with" block opened for reading, f.read() returns the entire file's contents as one string, f.readline() reads a single line at a time, and f.readlines() returns a list of all lines; you can also iterate directly over the file object line by line with a for loop, which is the most memory-efficient option for large files. For writing, f.write(text) writes a string to the file (it does not add a newline automatically, unlike print()).

Examples

Writing to a file, then reading it back line by line

Python
with open("notes.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")
    f.write("Third line\n")

with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())
Output
First line
Second line
Third line

Appending to an existing file and reading the full contents at once

Python
with open("notes.txt", "a") as f:
    f.write("Fourth line\n")

with open("notes.txt", "r") as f:
    contents = f.read()

print(contents)
Output
First line
Second line
Third line
Fourth line

Common Mistakes

  • Opening a file with mode "w" when "a" (append) was intended, which silently erases the file's previous contents.
  • Forgetting to use "with" and manually calling open()/close(), then leaking a file handle when an exception occurs before close() is reached.
  • Not stripping the trailing newline character when reading lines, leading to unexpected blank lines or formatting when printing them.
  • Trying to open a file for reading ("r") that does not yet exist, resulting in a FileNotFoundError instead of an empty result.

Exercise

In a temporary folder, write three lines to a text file, read them back, and print how many lines there are and the first line. Then append a fourth line and print the new number of lines.

Expected output: 3, first, 4 (one per line)

Python · starter code
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as folder:
    path = Path(folder) / "notes.txt"

    # TODO: write the lines "first", "second" and "third" to the file

    # TODO: read the lines back, print how many there are and the first one

    # TODO: append the line "fourth", read the file again and print the line count
    pass
Show hints
  • Mode "w" creates or overwrites the file, and mode "a" adds to the end.
  • file.read().splitlines() gives the lines without their line breaks.
Show solution
Python · solution
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as folder:
    path = Path(folder) / "notes.txt"

    with open(path, "w") as file:
        file.write("first\nsecond\nthird\n")

    with open(path) as file:
        lines = file.read().splitlines()
    print(len(lines))
    print(lines[0])

    with open(path, "a") as file:
        file.write("fourth\n")

    with open(path) as file:
        print(len(file.read().splitlines()))

Quick quiz

1. What happens when an existing file is opened with mode "w"?

  • A. New text is added at the end
  • B. It is opened read-only
  • C. An error is raised
  • D. Its contents are erased
Show answer

D. Use "a" to add to a file, or "x" to fail if the file already exists.

2. What does the with statement guarantee for a file?

  • A. That the file is closed when the block ends, even if an error occurs
  • B. That the file exists
  • C. That the file is read faster
  • D. That the file cannot be changed
Show answer

A. Closing also makes sure that buffered data is written.

3. What is the most memory-efficient way to process a very large text file?

  • A. file.read()
  • B. Looping over the file object, one line at a time
  • C. file.readlines()
  • D. Opening it twice
Show answer

B. read() and readlines() load the whole file into memory.

Interview questions

What are the main file modes in Python?

Show answer

"r" reads and is the default; the file must exist. "w" writes, creating the file or erasing its contents. "a" appends to the end. "x" creates a new file and fails if it exists. Adding "b" opens the file in binary mode, for images and other non-text data, and adding "+" allows both reading and writing.

Why should you pass encoding="utf-8" when opening a text file?

Show answer

Without it, Python uses the default encoding of the platform, which has differed between operating systems, so a file written on one machine could be read incorrectly on another, or fail with UnicodeDecodeError. Stating the encoding makes the behaviour the same everywhere. UTF-8 is the standard choice.

Key Points to Remember

  • open(filename, mode) returns a file object; common modes are "r" (read), "w" (overwrite), and "a" (append).
  • The "with" statement (a context manager) automatically closes the file when the block ends, even if an error occurs.
  • read() returns the whole file as one string; readlines() returns a list of lines; iterating the file object directly is most memory-efficient.
  • write() does not add a newline automatically — include "\n" explicitly when writing multiple lines.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering