Legends ofPythos
Claim your name
Writing Real Programs

Reading and writing files

Lesson 13 of 16

Watch the lesson5:34 · with Sigrid

Why files matter

Think of a file as a sticky note on your monitor. While your program runs, its variables live in RAM, the computer's short-term memory: fast, but wiped when the program ends. A file lives on the disk, which is long-term storage. You use files when you need data to survive after the script finishes—like saving game scores or keeping a running log of sensor readings.

The with statement

with open('greeting.txt', 'w') as f:
    f.write('Hello from Pythos\n')

# Here, the file is closed for you,
# even if an error happened above.
Opening and closing safely
open() returns a file object. You pass the filename and a mode. Mode 'w' means write: it creates the file or erases any existing content before writing. Using with guarantees that Python closes the file for you when the block ends, preventing data corruption.

Writing vs Appending

# Mode 'w': erases existing content first
with open('log.txt', 'w') as f:
    f.write('line one\n')

# Mode 'a': adds to the end (and makes
# the file if it isn't there yet)
with open('log.txt', 'a') as f:
    f.write('line two\n')
'w' overwrites; 'a' adds to the end
f.write(s) writes the string exactly as you give it. It does not add a newline character automatically. If you want each entry on its own line, include '\n' yourself at the end of your string.

Reading files

with open('log.txt', 'w') as f:
    f.write('line one\nline two\n')

# .read(): the whole file as one string
with open('log.txt') as f:
    text = f.read()
print(text)

# .readlines(): a list, one string per line
with open('log.txt') as f:
    lines = f.readlines()
for line in lines:
    print(line.strip())
Two ways to read: whole file or lines
By default, open() uses mode 'r' for reading. You can grab the whole file at once with .read(), or get a list of strings with .readlines(). Each string in that list includes its trailing newline character, so use .strip() to clean it up before printing.

Looping over files

fruits = ['apple', 'banana', 'cherry', 'date']
with open('words.txt', 'w') as f:
    for fruit in fruits:
        f.write(fruit + '\n')

# Read it back one line at a time
with open('words.txt') as f:
    for line in f:
        word = line.strip()  # drop the '\n'
        if len(word) > 5:
            print(f'Long fruit: {word}')

# Long fruit: banana
# Long fruit: cherry
Iterating line by line for large data
For large files, you can loop directly over the file object. Python reads it lazily—one line at a time—so your program doesn't load megabytes of text into memory all at once.

Your turn

0 of 3 solved

Exercise 1

+35 XP
Create a file called greeting.txt containing exactly one line: Hello from Pythos. Use the with statement and mode 'w'. Then read it back with .read() into a variable named content, so that content.strip() equals the greeting.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+35 XP
Append three lines to log.txt using mode 'a'. The final file should contain exactly these three lines in order: first, second, third. Read the file with .readlines() into a list called lines so that [l.strip() for l in lines] equals ['first', 'second', 'third'].
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+35 XP
Write these five-a-side match scores to scores.txt, one per line: 2, 15, 4, 7, 6.
Then open the file for reading and loop over it directly with for line in f:. Count how many lines contain the digit '5' and store that number in count.

in works on text too: 'a' in 'cat' is True, because the text 'cat' contains an 'a'.
Write your Python here.

Run your code to check it against the tests.