GCSE · Computer Science · Eduqas · Spec C500QS

File handling: read into a variable

You read a name from a file and compare it with what the user typed. The program insists they differ. So what is hiding in that variable?

Computer Science · Reading a file

What does each readline() hand back?

pets.txt holds three lines: cat, dog, fox. The first two end in a newline. The last, fox, has no newline after it. Step through, and call each string before the table shows it. Nothing is run: every value is the lesson's.

f = open("pets.txt", "r")
line = f.readline() # call 1
line = f.readline() # call 2
line = f.readline() # call 3
line = f.readline() # call 4
if line == "":
print("No more lines")

Variables

f=pets.txt, open in read mode

Step 1. We open pets.txt in read mode. f is the file object we read through. Nothing has been read yet, so there is no line variable. This first step is worked for you.

Step 1 of 7Called right: 0 of 5

Two ways to read

read()vsreadline() or for line in f:

Same file, two different things landing in your variable.

Focus

What the variable holds

read()

The whole contents of the file, as one single string

readline() or for line in f:

One line of the file at a time, as a string

The insight

contents = f.read() gives you everything at once. line = f.readline() gives you just the next line.

Where the newlines are

read()

Inside the string: a \n at the end of every line that ends in one

readline() or for line in f:

On the end of each line as it arrives, if the line has one

How it moves on

read()

One call takes the lot

readline() or for line in f:

Each readline() call moves on a line. A for loop over the file does that stepping for you

What is held in memory

read()

The whole file is sitting in the variable

readline() or for line in f:

Only the line you are working on has to be held, not the whole file at once

When it suits

read()

A small file you want to process as one block of text

readline() or for line in f:

Processing each line (record) separately

Computer Science · What reading does

What has just happened to the data?

A program runs f = open("notes.txt", "r") and then contents = f.read(). The file notes.txt holds three lines of text.

Which idea is closest to what you think reading has done?
How sure are you?

Exam line: Reading copies the data into the program's memory, and the variable holds that copy.

Computer Science · The invisible newline

Same name, still no match

names.txt starts with the name Maya. Maya types Maya, but this program prints No match. Which line is the fault?

A student's program — which line goes wrong?

Exam line: readline() keeps the \n. Use strip() (or rstrip("\n")) before you compare, display or store the value.

Computer Science · Reading numbers from a file

The total that came out wrong

scores.txt has a 5 on its first line and a 3 on its second. This program should print their total. Press Run, read what comes back, then pick the replacement for line 4.

Python 3
  1. f = open("scores.txt", "r")
  2. a = f.readline().strip()
  3. b = f.readline().strip()
  4. print(a + b)

The outputs and messages are what Python 3 gives for exactly this code.

Computer Science · Put it together

Finish the scores program

Finish this program so it adds up every score in scores.txt. The file holds one whole number on each line.

  1. total = 0Start the running total at zero.
  2. missing step
Which line is step 2?

Exam line: Open with "r", loop with for line in f:, then strip and cast each line before you use it as a number.

WHAT YOU'VE LEARNED

A quick recap of today's lesson.

Get a file's contents into your program, and spot the surprises that come with them.

What you need to know

  • Reading a file copies its data into the running program's memory, where a variable holds it so the program can process it.
  • In Python 3 you read through the file object of a file that has already been opened for reading, in read mode "r".
  • f.read() returns the whole contents of the file as one single string, so contents = f.read() stores it in a variable.
  • That string keeps a newline, "\n", at the end of each line that ends in one. The last line may have no "\n".
  • Have a goA classmate says, completely confidently: "If my file has two lines, f.read() gives me a list of two strings." What does it really give?

    One single string, with the \n of line 1 sitting inside it.

    read() returns the whole contents as a single string. The newlines are just characters inside it, not the edges of list items.

  • f.readline() returns the next single line as a string, including its "\n" if the line has one.
  • Each readline() call moves on through the file, so successive calls return successive lines.
  • At the end of the file, readline() and read() return the empty string "", which a program can test for.
  • A loop such as for line in f: reads one line at a time and puts each line in turn into line.
  • Have a goA file holds red, green and blue, one per line, each line ending in a newline. In for line in f:, what exactly does line hold on the second pass?

    "green\n"

    The loop puts each line in turn into line, and a line that ends in a newline keeps its \n. The second pass gives the second line.

  • strip() (or rstrip("\n")) removes the trailing newline: name = f.readline().strip(). Do it before you display, compare or store the value.
  • Text read from a file is always a str, even when it looks like a number. Cast it with int() or float() to use it as one.
  • Have a goYour friend says score = f.readline() "obviously gives me a number", because the line is only digits. What type is score, and what fixes it?

    It is a str. Cast it: score = int(f.readline()).

    Data read from a text file is always a str, even when the characters represent a number. int() converts it, and float() would do it for a real number.

The big picture

Reading a file copies its data into the program's memory, where a variable holds it as a string. read() hands over the whole file at once. readline() and a for loop hand over one line at a time, newline included. At the end of the file you get the empty string. Strip the newline and cast the text before you use it as a number.

Key points

1Reading copies the file's data into memory, where a variable holds it.
2read() returns the whole contents as one string. readline() returns the next single line, and each call moves on.
3Lines keep their "\n" until you strip them. The last line of a file may have none.
4The empty string "" means the end of the file has been reached.
5Reading the whole file suits a small file processed as one block of text. Line by line suits processing each line (record) separately.
6Data from a text file is always a str. Cast it with int() or float(), and int("ten") causes a ValueError, so the data must match the type.

Worked example

Problem

names.txt holds two lines, Ann and then Raj. Ann's line ends in a newline. Raj's line is the last and has no newline. After contents = f.read(), exactly what does contents hold, and how many characters is that?

⚠ Watch out

Treating file data as ready to use. A line arrives with its \n, numbers arrive as str, and each readline() call moves on instead of giving the same line again.

🧠

Memory hook

Every read hands you a str with its \n still on: strip it, then cast it, then use it.

✓

Check yourself

Without looking back: a file has three lines and each one ends in a newline. Say what four successive readline() calls return. Then say how you would turn the second result into a whole number.

Flashcards

(13)
What does reading a file do?
It copies data stored in the file into the running program's memory, where a variable holds it so the program can process it.
What must be true of a file before Python 3 can read it?
It must already be opened for reading, in read mode "r". You then read through its file object.
What does read() return?
The whole contents of the file as a single string, e.g. contents = f.read().
Where do newline characters appear in the string from read()?
At the end of each line that ends in one. The last line may have no trailing newline, so the string may not end in "\n".
What does readline() return?
The next single line of the file as a string, with its trailing "\n" if the line has one.
You call readline() three times in a row. What do you get?
Three successive lines. Each call moves on through the file.
What does readline() return at the end of the file, and why does that matter?
The empty string "". A program can test for it to detect the end of the file.
What does for line in f: do?
Reads the file one line at a time, placing each line in turn into the loop variable.
When does read() suit, and when does line-by-line suit?
read(): a small file processed as one block of text. Line by line: processing each line (record) separately, without holding the whole file in memory at once.
How do you remove the trailing newline from a line you have read?
Use strip() (or rstrip("\n")), e.g. name = f.readline().strip(), before you display, compare or store it.
What data type is text read from a file?
Always str, even when the characters represent a number.
How do you use a line from a file as a whole number or a real number?
Cast it: int() for an integer, float() for a real number, e.g. score = int(f.readline()).
What happens with int("ten")?
A run-time error (ValueError). The text must represent a valid number, so the file's data must match the type you convert to.

Tap any card to flip it, or use Study as deck to go through them one at a time. In the full lesson these run as a spaced-repetition deck — you rate each card Hard, Good or Easy and the tricky ones keep coming back until they stick.

Learning with Lightbulb is opening soon

You can use this lesson now. Join the waitlist and we'll let you know when the full Lightbulb experience is ready.

Keep me posted

More Eduqas GCSE Computer Science topics

See the full Eduqas Computer Science curriculum →

How this lesson was checked. This Eduqas GCSE Computer Science (specification C500QS)lesson was published through Lightbulb Learning's human-designed editorial process — the educational standards, accuracy rules and publication checks it must pass were authored and approved by Philip Halpin. It passed subject-specific assessment, automated educational checks and technical publication verification before going live (publication checks completed 16 November 2026). Published pages are monitored, human spot-checking is ongoing across the lesson library, and anything found wrong is corrected or withdrawn. How our lessons are made and checked. Spotted a mistake? Email hello@lightbulblearning.co and we'll review it.