Legends ofPythos
Claim your name
Writing Real Programs

Reading and writing files

Lesson 13 of 16

Watch the lesson1:25 · with Sigrid

Why files matter

Think of a file as a sticky note on your monitor. Your program runs in RAM, which is like short-term memory: fast but temporary. 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')

# The file is closed automatically here, even if an error occurs 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': appends after whatever exists, creating file if needed
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

# The two files from the blocks above
with open('greeting.txt', 'w') as f:
    f.write('Hello from Pythos\n')
with open('log.txt', 'w') as f:
    f.write('line one\nline two\n')

# Read entire file as one single string
with open('greeting.txt') as f:
    text = f.read()
print(text)

# Read all lines into a list (each line keeps its trailing newline)
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

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

# Read it back one line at a time (memory-friendly for big files)
with open('words.txt') as f:
    for line in f:
        word = line.strip()      # each line still carries its '\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 RAM 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.
Write your Python here.

Run your code to check it against the tests.