Reading and Writing Files

Python 3.12 · ✓ verified by execution on 2026-07-23

Reading and Writing Files

In Python, interacting with the file system is built right into the language.

Opening Files

The open() function returns a file object you can read from or write to. If the file can’t be opened — for example, it doesn’t exist — Python raises an OSError (in practice a specific subclass like FileNotFoundError):

python
try:
    f = open('does_not_exist.txt')
except OSError as e:
    print(f'Error: {type(e).__name__}')
Output
Error: FileNotFoundError

The with Statement

Always open files with a with statement. It guarantees the file is closed automatically when the block ends — even if an error happens inside — so you never leak an open file handle or lose unsaved data:

python
with open('temp.txt', 'w') as f:
    f.write('test')
print(f'Is file closed? {f.closed}')
Output
Is file closed? True

Read and Write Modes

The second argument to open() is the mode. It defaults to 'r' — open for reading in text mode — so if you only want to read, you can leave it out:

python
with open('temp.txt', 'w') as f:
    f.write('Default mode test')
with open('temp.txt') as f:
    print(f.read())
Output
Default mode test

There are two ways to write. 'w' (write) truncates the file — it wipes any existing contents the moment you open it — while 'a' (append) keeps what’s there and adds to the end. Reach for 'w' to start fresh and 'a' to add on:

python
with open('temp.txt', 'w') as f:
    f.write('Hello World!')
with open('temp.txt', 'r') as f:
    print(f.read())
Output
Hello World!

You can also append to an existing file:

python
with open('temp_append.txt', 'w') as f:
    f.write('First.')
with open('temp_append.txt', 'a') as f:
    f.write(' Second.')
with open('temp_append.txt', 'r') as f:
    print(f.read())
Output
First. Second.

Iterating File Lines

To read a file line by line, just loop over the file object directly. This is the fastest and most memory-efficient way — Python reads one line at a time instead of loading the whole file into memory at once:

python
with open('temp_lines.txt', 'w') as f:
    f.write('line1\nline2\nline3')
with open('temp_lines.txt') as f:
    for line in f:
        print(line.strip())
Output
line1
line2
line3

Edge Cases

Check yourself

You don't need to close a file if your script ends soon anyway.

Reveal answer

While the OS usually cleans up, relying on it is a bad habit that leads to resource leaks in larger programs. Always use `with open(...)`. — While the OS usually cleans up, relying on it is a bad habit that leads to resource leaks in larger programs. Always use `with open(...)`.

`f.read()` is always the best way to read a file.

Reveal answer

If the file is massive, `f.read()` will load the entire thing into memory, potentially crashing your program. Looping over the file object is safer. — If the file is massive, `f.read()` will load the entire thing into memory, potentially crashing your program. Looping over the file object is safer.

`w` mode will safely add text to an existing file.

Reveal answer

`w` mode completely truncates (erases) the file before writing. Use `a` (append) mode to add text to the end. — `w` mode completely truncates (erases) the file before writing. Use `a` (append) mode to add text to the end.

File objects return lines without the newline character.

Reveal answer

File iteration and `readline()` leave the trailing `\n` intact. You typically need to call `.strip()` to remove it. — File iteration and `readline()` leave the trailing `\n` intact. You typically need to call `.strip()` to remove it.

Challenges

Challenge 1 +25 XP

Write a script that opens `message.txt` in read mode, reads the first 5 characters, and prints them.

python
  • Test 1 — expects "Pytho"
Show solution (0 XP)
# Setup file
with open('message.txt', 'w') as f:
    f.write('Python is awesome')

# Open message.txt in read mode and print the first 5 characters
with open('message.txt', 'r') as f:
    print(f.read(5))

Challenge 2 +25 XP

Append the string ' Done.' to the end of `log.txt`.

python
  • Test 1 — expects "Task 1. Done."
Show solution (0 XP)
# Setup file
with open('log.txt', 'w') as f:
    f.write('Task 1.')

# Append ' Done.' to log.txt
with open('log.txt', 'a') as f:
    f.write(' Done.')

# Verify
with open('log.txt', 'r') as f:
    print(f.read())