Python Basics

File Handling in Python

Programs often save data to files and read it back. open() returns a file object, and the mode decides whether you read, write or append.

What is File Handling?

Programs often save data to files and read it back. open() returns a file object, and the mode decides whether you read, write or append.

Write, append and read text files in Python with open() and with.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
# "w" creates the file (or empties it) and opens it for writing.
with open("notes.txt", "w") as file:
    file.write("first line\n")
    file.write("second line\n")

# "a" appends to the end of an existing file.
with open("notes.txt", "a") as file:
    file.write("third line\n")

# "r" (the default) reads. read() returns the whole file as one string.
with open("notes.txt") as file:
    print(file.read())

# Loop over a file to read it line by line.
with open("notes.txt") as file:
    for number, line in enumerate(file, start=1):
        print(number, line.strip())

# "with" closes the file automatically, even if an error happens.

Expected output

first line
second line
third line

1 first line
2 second line
3 third line

How it works

"w" replaces the file's contents, "a" adds to the end and "r" reads. The with block closes the file automatically, even when an error happens.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges