GCSE · Computer Science · Eduqas · Spec C500QS

File handling: read into an array

Print a line you read from a file and a blank line appears that was never there. One invisible character is to blame. Let's catch it.

Computer Science · Files

Read pets.txt into a list, one line at a time

pets.txt has three lines: cat, dog and fox. Version A: Enter was pressed after every line. Version B: Enter was pressed after cat and dog, but nobody pressed it after fox. Pick a version, then commit to each marked value before the table shows it.

items = []
file = open("pets.txt")
for line in file:
items.append(line)
file.close()
print(len(items))
first = items[0]
lineitemsfirst
[]

Step 1. Before the loop, items is an empty list. This first step is worked for you.

Step 1 of 11Called right: 0 of 4

Computer Science · Four ways to read

Same file, four routes. What do you get?

For each route, tick every property it has, then check. Think about what the file would look like when it arrives in Python.

for line in file: items.append(line)
items = file.readlines()
text = file.read()
items = file.read().splitlines()

​

Computer Science · Lists of lists

One file, three views: where does each item live?

  1. 1 Explore
  2. 2 Translate

Model. The file, the list of lists and the table all hold the same three pupils. The newline on each line has already been removed, so only the items are shown.

Step 1 · Explore

Select Wales, then Ana, then 14. In each view, see where the same item sits, and read its row and column off the table.

Linked parts: select one to follow it through every representation

Sam,15,

,16,Kent

Raj,,Leeds

Each line holds items separated by commas.

Linked parts tried: 0 of 2.

Computer Science · Debugging

The stubborn \n: find the faulty line

This program should store each pupil as ["Sam", "15", "Wales"]. But it prints "Wales" and then an unexpected blank line, and the length it prints is 6, not 5. Which line is the fault?

A student's program (pupils.txt holds Sam,15,Wales on its first line) — which line goes wrong?

Computer Science · Strings and numbers

Press Run: why will it not add up?

scores.txt holds three scores, one per line: 12, 15 and 9. The program should print their total, 36. Run it, read what happens, then choose the fix for the flagged line.

Python 3
  1. file = open("scores.txt")
  2. total = 0
  3. for line in file:
  4. total = total + line
  5. file.close()
  6. print(total)

The messages and outputs are what Python 3.13 gives for this exact code, with scores.txt holding the whole numbers 12, 15 and 9 on separate lines.

Computer Science · Write it yourself

Put it all together

A text file called pupils.txt holds one pupil on each line, written as name,age (for example Sam,15). Write a Python 3 program that reads the file into a list of lists, one inner list per line with the line ending removed, and then prints the first pupil's age plus 1. [7 marks]

0 words · your answer stays on this page and is not sent anywhere.

WHAT YOU'VE LEARNED

A quick recap of today's lesson.

Get a text file into a Python list, one line at a time, and meet the invisible \n on the way.

What you need to know

  • Reading a file into an array means filling a Python 3 list, usually one item per line of the file.
  • Loop over the open file with for line in file: and each pass hands you one line, as a string.
  • Start with items = [], then items.append(line) adds each line to the end of the list.
  • Have a goA file has 6 lines. The loop runs items.append(line) once for every line. How long is the list at the end?

    6 items.

    One append per pass and one pass per line, so the list ends up as long as the file has lines.

  • Afterwards, items[0] is the first item (counting starts at 0) and len(items) says how many items you read.
  • Each line normally arrives with a hidden \n on the end; the last line of a file may not have one.
  • Have a goYour classmate says the first line, cat, is stored as a three-letter string. Count honestly: how many characters is the stored line?

    Four: c, a, t and the newline.

    The \n is a real character that comes with the line, even though you cannot see it. (The last line of a file may not have one.)

  • readlines() builds the list for you; read() gives the whole file as one string, and splitlines() on that string drops the \n.
  • strip() removes whitespace at both ends, \n included; rstrip("\n") removes only the trailing newline.
  • When a line holds several items, line.split(",") cuts it into a list, so clean the \n off first or the last item keeps it.
  • Split every line and append the result and you get a list of lists: records[i][j] is item j of line i.
  • Everything read from a file is a string, so convert a numeric item with int() or float() before calculating or comparing.
  • Have a goThe line from the file is 7. Your program works out line + 1. Does that give 8?

    No. It stops with a type error.

    The 7 read from a file is a string, and a string cannot be added to a number. You would need int(line) + 1.

The big picture

A file read into Python becomes a list of strings, usually one per line. Each string normally still carries its \n, and numbers arrive as text, so you clean lines with strip() or rstrip("\n") before splitting them and convert numeric items with int() or float() before using them.

Key points

1A file read into a list gives one string per line, and each string normally ends in \n.
2The loop for line in file: with items.append(line) grows the list by one item per line.
3Remove the line ending with strip() or rstrip("\n") before you split a line.
4split(",") turns a line into a list, and a list of those lists is indexed as records[i][j].
5Items from a file are strings: use int() or float() before using them as numbers.

Worked example

Problem

basket.txt holds three lines: apples, bread and milk. Nobody pressed Enter after milk. Read it into a list with the line endings removed, then say what len(items) and items[1] are.

⚠ Watch out

Thinking each line arrives exactly as it looks in the file, with numbers already numbers. In fact every line is a string that normally ends in \n, so clean it before splitting and convert numbers before using them.

🧠

Memory hook

Every line wears an invisible \n, and is always text: strip it, split it, then convert it.

✓

Check yourself

scores.txt has three lines: 4, 7 and 12. The loop appends each line with no cleaning. What does items hold, and what must you do before adding the scores?

Flashcards

(13)
In Python 3, what does reading a file into an array mean?
Putting the contents of the file into a list, so each item can be processed later in the program.
What is the most common way to fill the list from a file?
One item per line, so the list holds as many items as the file has lines.
What does for line in file: give you on each pass?
The next line of the file, as a string.
Starting from items = [], how does a line get into the list?
items.append(line) adds it to the end of the list.
What does the readlines() method return?
A list containing every line of the file, each line as a string.
What is \n, and where does it hide?
The newline character. Each line read from a text file normally keeps it at the end; the last line may not have one.
strip() or rstrip("\n"): what is the difference?
strip() removes leading and trailing whitespace, \n included. rstrip("\n") removes only the trailing newline.
What do read() and splitlines() give you together?
read() returns the whole file as one string, and splitlines() on that string gives a list of lines with the line endings removed.
What does "Sam,15,Wales".split(",") give?
["Sam", "15", "Wales"]: a list of separate items.
In a list of lists, what does records[i][j] mean?
Item j of line i, which is how a two-dimensional array is indexed.
Which goes first, stripping the \n or splitting the line?
Strip first. Otherwise the last item of each line keeps the \n.
What type is a number you read from a text file, and how do you fix it?
It is a string. Convert it with int() or float() before a calculation or a numeric comparison.
Once the list is built, what do items[0] and len(items) give?
items[0] is the first line (counting starts at 0), and len(items) is the number of items read.

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.