Python File Handling
Core Python Iteration and Files

Python File Handling

1Python File Handling: overview

File handling means using open() to connect your program to a file, reading text from it or writing text into it, and then closing it so the work is saved.

GoalBy the end you can write, append and read text files with open() and a with block, choose the right mode, loop over the lines of a file, and handle a file that does not exist.

Before this lesson: Python Strings, Python for Loops, Python Exceptions: try, except, else and finally

2Python File Handling: diagram

Python File Handlingopen("notes.txt", "w")"w" write, "a" append, "r" readf.write("Buy milk\n")text goes into the fileend of with blockfile closed, text savedlateropen("notes.txt", "r")FileNotFoundError if missingf.read() / for line in ftext comes back as strend of with blockclosed automatically
Every file goes through the same three stages: open it in a mode, read or write text, then close it — a with block does the closing for you. On this site the file system starts empty, so a file must be written before it can be read.

3Python File Handling: explained step by step

Variables disappear when a program stops. Files let you keep data — notes, settings, scores — and read it back later. Python's built-in open() function gives you a file object that you can write text into or read text out of.

Open files with with

The safest way to open a file is in a with block. When the indented block ends, Python closes the file for you, even if an error happens halfway through. Closing matters: written text can sit in a memory buffer and only reach the file when it is closed.

Python
with open("todo.txt", "w") as f:
    f.write("Buy milk\n")
    f.write("Call Sam\n")

with open("todo.txt") as f:
    print(f.read())

write() never adds a line break, so end each line with \n yourself.

Choose the right mode

The second argument of open() is the mode:

  • "r" — read. This is the default, and the file must already exist.
  • "w" — write. Creates the file, or wipes it empty if it already exists.
  • "a" — append. Adds to the end and keeps what is already there.

Opening with "w" when you meant "a" is the classic way to lose data, so pick the mode on purpose.

Read line by line

You can loop over a file object: each pass gives you one line, including its \n. Use .strip() to remove it. f.readlines() gives you all lines as a list, and f.read() gives you the whole file as one string.

Python
with open("scores.txt", "w") as f:
    f.write("Asha,82\nBen,67\n")

with open("scores.txt", "a") as f:
    f.write("Chen,91\n")

with open("scores.txt") as f:
    for line in f:
        name, score = line.strip().split(",")
        print(name, "scored", int(score))

Everything you read from a text file is a string. Convert it with int() or float() before doing maths.

When the file is missing

Reading a file that does not exist raises FileNotFoundError. If a missing file is a normal situation — say, the first time your program runs — catch it with try/except and fall back to a default.

Files in your browser

The code on this site runs inside your browser, which has its own temporary, in-memory file system. It starts empty, cannot see the files on your computer, and is cleared when you reload the page. That is why every example here writes a file before reading it. On your own computer, exactly the same code reads and writes real files in the current folder.

Quick reference: Python File Handling

4Python File Handling: syntax

with open("file.txt", "w") as f:   # "w" write (overwrite), "a" append
    f.write("some text\n")         # strings only; add \n yourself

with open("file.txt") as f:        # "r" (read) is the default mode
    text = f.read()                # whole file as one string
    # lines = f.readlines()        # list of lines
    # for line in f: ...           # one line at a time

5Python File Handling: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
entries = ["Mon: 5 km run", "Wed: 30 min swim", "Fri: 8 km run"]

with open("workouts.txt", "w") as f:
    for entry in entries:
        f.write(entry + "\n")

with open("workouts.txt", "a") as f:
    f.write("Sun: yoga\n")

with open("workouts.txt") as f:
    lines = f.readlines()

print("File closed:", f.closed)
print("Lines in file:", len(lines))
for number, line in enumerate(lines, start=1):
    print(number, line.strip())
Expected outputFile closed: True
Lines in file: 4
1 Mon: 5 km run
2 Wed: 30 min swim
3 Fri: 8 km run
4 Sun: yoga

7Python File Handling: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1A list of three workout notes is created. This is the data we want to save.
  2. Line 3open("workouts.txt", "w") creates the file (or empties it if it already exists) and names the file object f.
  3. Line 4-5Each entry is written with "\n" added, because write() does not start a new line by itself.
  4. Line 7-8Mode "a" keeps the three existing lines and adds "Sun: yoga" at the end.
  5. Line 10-11With no mode given, the file opens for reading. readlines() returns a list of 4 strings, each still ending in "\n".
  6. Line 13We are outside the with block now, so f.closed is True — Python closed the file automatically.
  7. Line 14len(lines) counts the lines that came back from the file: 4.
  8. Line 15-16enumerate(..., start=1) numbers the lines from 1, and strip() removes the trailing newline so print() does not add blank lines.

8Python File Handling: common mistakes

Reading a file that was never created

✗ Wrong

with open("diary.txt") as f:
    print(f.read())
FileNotFoundError: [Errno 44] No such file or directory: 'diary.txt'

✓ Right

try:
    with open("diary.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("No diary yet - creating one.")
    with open("diary.txt", "w") as f:
        f.write("Day 1\n")

Mode "r" needs an existing file. Write the file first, or catch FileNotFoundError when a missing file is expected. Remember that the browser's file system starts empty.

Using "w" when you meant "a"

✗ Wrong

with open("log.txt", "w") as f:
    f.write("first visit\n")
with open("log.txt", "w") as f:
    f.write("second visit\n")
with open("log.txt") as f:
    print(f.read())
Prints only 'second visit' — the first line was wiped

✓ Right

with open("log.txt", "w") as f:
    f.write("first visit\n")
with open("log.txt", "a") as f:
    f.write("second visit\n")
with open("log.txt") as f:
    print(f.read())

Mode "w" empties the file every time it is opened. Use "a" to add to the end of an existing file.

Passing a number to write()

✗ Wrong

score = 95
with open("best.txt", "w") as f:
    f.write(score)
TypeError: write() argument must be str, not int

✓ Right

score = 95
with open("best.txt", "w") as f:
    f.write(f"{score}\n")

Text files store strings only. Convert the value with str() or an f-string, and add the newline yourself.

9Python File Handling: exercises

Write your answer, then press Check. The checks run in your browser.

1. Save a list to a file

Write code Easy

Complete the function save_lines(filename, lines) so that it writes every string in lines to the file, one per line (each followed by \n). If the file already exists, its old contents should be replaced.

Your code
def save_lines(filename, lines):
    # open the file in write mode and write each line followed by "\n"
    pass

save_lines("shopping.txt", ["eggs", "rice", "apples"])

2. Predict what survives

Predict the output Medium

The file is opened four times with different modes. Type exactly what the last line prints.

Read this code
with open("pets.txt", "w") as f:
    f.write("cat\n")
with open("pets.txt", "a") as f:
    f.write("dog\n")
with open("pets.txt", "w") as f:
    f.write("fish\n")
with open("pets.txt", "a") as f:
    f.write("bird\n")

with open("pets.txt") as f:
    print(f.read().split())

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Do I still need to call close() if I use with open()?

No. The with block closes the file automatically when the indented code finishes, even if an error occurs. Without with you must call f.close() yourself, and it is easy to forget.

Why do I get FileNotFoundError when the file is on my computer?

On this site Python runs in your browser, which has its own temporary file system and cannot see your computer's files, so create the file in code first. In desktop Python, a relative name like data.txt is looked up in the current working directory, which may not be the folder your script is in.

What is the difference between read(), readline() and readlines()?

read() returns the whole file as one string, readline() returns the next single line, and readlines() returns a list of all lines. For large files, looping with for line in f is best because it reads one line at a time.

Further reading

10Next lesson

Up nextPython with StatementThe with statement runs setup code before a block and guaranteed cleanup code after it, even when the block fails, by u…

Related:
Python with StatementPython pathlibWorking with JSON in PythonPython CSV Files

← Python itertools · All Iteration and Files lessons · Practise in the IDE