TalentJR

🐍 Python for kids · Class 7 · Lesson 16 of 18 · Free

File Handling – Save and Read Your Data

⏱ About 35 minutes · ▶ run real Python here — nothing to install · no sign-in

In this lesson you will

  • Write text to a file and read it back with open() and with.
  • Choose the right mode: "w" to write, "a" to append, "r" to read.
  • Read a file line by line and turn the lines into a list of data.

Every program so far forgets everything when it stops. Your game scores, your to-do list, your quiz marks: all gone! Files let a program write things down, like a notebook it can open again tomorrow.

What is file handling in Python?

Variables live in the computer's memory. When the program ends, that memory is cleared.

A file is stored on the disk, so it stays after the program ends. File handling means creating, writing and reading files.

open() takes a file name and a mode. "w" means write, and it creates the file if needed.

write() puts text in the file. close() finishes the job and saves everything properly.

🎬 How Python thinks — step 1 of 9Python is about to run line 1
▶f = open("diary.txt", "w")
2f.write("Today I learned recursion.\n")
3f.write("Tomorrow: files!\n")
4f.close()
5
6f = open("diary.txt", "r")
7text = f.read()
8f.close()
9print(text)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Today I learned recursion.
Tomorrow: files!

💡 write() does not add a new line by itself. Put \n at the end of each line you write.

Why should I use with open() in Python?

It is easy to forget close(). Then some text may never reach the file.

with open(...) as f: opens the file and closes it automatically when the indented block ends.

It still closes the file even if an error happens inside. So most Python programmers always use with.

🎬 How Python thinks — step 1 of 10Python is about to run line 1
▶with open("poem.txt", "w") as f:
2 f.write("Twinkle twinkle little star\n")
3 f.write("How I wonder what you are\n")
4
5with open("poem.txt", "r") as f:
6 poem = f.read()
7print(poem)
8print("Characters in the file:", len(poem))
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Twinkle twinkle little star
How I wonder what you are

Characters in the file: 54

What is the difference between write mode and append mode?

Mode "w" starts a fresh file every time. Anything already in it is wiped out.

Mode "a" means append. It keeps the old text and adds new text at the end.

Use "a" for things that grow, like a log of daily steps or a list of high scores.

🐍 Python — you can edit this code
Output
Monday 4500
Tuesday 6200
Wednesday 5100

💡 If you leave out the mode, Python uses "r" for reading.

How do I read a file line by line?

A for loop can walk through an open file. Each time round, it gives you one line.

Every line still ends with \n. strip() removes it, so print() does not show blank lines.

Here we save a shopping list, then number each item as we read it back.

🎬 How Python thinks — step 1 of 17Python is about to run line 1
▶with open("shopping.txt", "w") as f:
2 f.write("rice\ndal\nghee\n")
3
4number = 1
5with open("shopping.txt") as f:
6 for line in f:
7 print(number, line.strip())
8 number += 1
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
1 rice
2 dal
3 ghee

How do I save numbers in a file and read them back?

Files only store text. So convert numbers with str() before writing them.

When you read them back, they are strings again. Use split() to break a line into parts, then int() to get numbers.

This is how real apps save data: one record per line, with a comma between the fields.

🐍 Python — you can edit this code
Output
Asha scored 88
Kabir scored 95
Neha scored 79
Class total: 262

💡 A file like this, with commas between values, is called a CSV file. Spreadsheets can open it.

Where are files saved when I run code on this page?

On your own computer, the file appears in the same folder as your .py program.

On this page, Python runs inside your browser. Its files live in the browser's memory and vanish when you reload.

That is why every example here writes a file first and then reads it. Try the same code on a laptop to see real files.

🐍 Python — you can edit this code
Output
['Finish maths homework\n', 'Practise Python\n']
Tasks to do: 2

💡 readlines() gives a list with one string per line. Each string still ends with \n.

🤔 Predict the output

Think like Python: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

with open("a.txt", "w") as f:
    f.write("Hi")
    f.write("There")
with open("a.txt") as f:
    print(f.read())

Question 2. The file is opened in "w" mode twice. What does this print?

with open("b.txt", "w") as f:
    f.write("one\n")
with open("b.txt", "w") as f:
    f.write("two\n")
with open("b.txt") as f:
    print(f.read().strip())

Question 3. What does this print?

with open("c.txt", "w") as f:
    f.write("5\n7\n")
with open("c.txt") as f:
    lines = f.readlines()
print(len(lines), lines[0].strip() + lines[1].strip())

🧩 Your challenge

Make a high-score saver. Ask for 3 players' names and scores, and append each as a line "name,score" to scores.txt. Then read the file back and print the player with the highest score.

Expected output (with the inputs given):
Player name: Ishaan
Score: 340
Player name: Tara
Score: 510
Player name: Dev
Score: 275
High score: Tara with 510
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

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

FileNotFoundError: [Errno 2] No such file or directory: 'homework_notes.txt'

✅ Right

with open("homework_notes.txt", "w") as f:
    f.write("Read chapter 4\n")
with open("homework_notes.txt") as f:
    print(f.read())

Reading needs a file that already exists. Create it with "w" first, or check the spelling of the name.

❌ Wrong

score = 95
with open("score.txt", "w") as f:
    f.write(score)

TypeError: write() argument must be str, not int

✅ Right

score = 95
with open("score.txt", "w") as f:
    f.write(str(score))

write() accepts only strings. Convert numbers with str() first.

❌ Wrong

for day in ["Mon", "Tue", "Wed"]:
    with open("days.txt", "w") as f:
        f.write(day + "\n")
with open("days.txt") as f:
    print(f.read())

No error message – but the file holds only Wed, not all three days.

✅ Right

with open("days.txt", "w") as f:
    for day in ["Mon", "Tue", "Wed"]:
        f.write(day + "\n")
with open("days.txt") as f:
    print(f.read())

Mode "w" wipes the file each time round the loop. Open the file once, before the loop, so every day goes into the same fresh file.

📌 Remember

  • Files keep data after a program ends; variables do not.
  • open(name, mode) opens a file: "r" to read, "w" to write fresh, "a" to add at the end.
  • with open(...) as f: closes the file for you, even if an error happens.
  • write() needs strings and adds no new line, so add \n yourself.
  • A for loop reads a file line by line; strip() removes the \n.
  • Save records as "name,value" lines and use split() and int() to read them back.

Finished the quiz and the challenge?

Questions students ask

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

read() gives the whole file as one string. readline() gives the next single line. readlines() gives a list of all lines.

Does "w" mode delete my file?

It empties the file and starts fresh. The old content is lost, so use "a" when you want to keep it.

Can Python open Word or Excel files?

Plain open() is for text files like .txt and .csv. Special modules are needed for Word, Excel or images.

How do I check if a file exists before reading it?

You can use os.path.exists("name.txt"). Or catch FileNotFoundError with try and except, which you will learn next lesson.