Session XP: 0
Spec 6.4.2Paper 2 (write Python) and Paper 1 (read Python)

File Handling

Reading and writing CSV text files in Python: open, read, write, append, close, and splitting lines on commas.

—
Best score
—
Last attempt
Best attempt progress
0
XP earned
Watch first
Craig 'n' Dave · Edexcel 1CP2The use of basic file handling operations (14:42)
Reference & Examples

Why use files? — fill in the table

PointDetail
Persistent storage
Between runs
Common uses
CSV file

File commands in Python — fill in the table

CommandMeaning
file = open("data.txt", "r")
file = open("data.txt", "w")
file = open("data.txt", "a")
for line in file:
file.write(text)
file.close()

Working with CSV lines — fill in the table

CommandMeaning
line.strip()
line.split(",")
",".join(fields)
Types
Record and field

Rules to remember

  • Open the file, process it, then close it.
  • Mode "w" erases what was there. Use "a" to keep old data.
  • A line read from a file ends with a newline, so strip it.
  • Fields from a CSV line are strings. Convert before adding up.
  • Check the PLS you are given: it lists the file commands you can use.
Writing records to a CSV file
# each record is name,score
file = open("scores.csv", "w")
for i in range(3):
    name = input("Name: ")
    score = input("Score: ")
    file.write(name + "," + score + "\n")
file.close()
print("Scores saved.")
Reading records back
file = open("scores.csv", "r")
for line in file:
    fields = line.strip().split(",")
    name = fields[0]
    score = int(fields[1])
    print(name, "scored", score)
file.close()
Reading and processing (find the average)
total = 0
count = 0
file = open("scores.csv", "r")
for line in file:
    fields = line.strip().split(",")
    total = total + int(fields[1])
    count = count + 1
file.close()
if count > 0:
    print(total / count)
Appending a new record
file = open("scores.csv", "a")
file.write("Sam,72\n")
file.close()
Exam practice — 6 questions · 14 marks · 1CP2 Paper 2 style
⚡ In the real Paper 2 you type and run Python on screen. Here, type your Python answer and the AI marks it against the mark points. Check the Programming Language Subset (PLS) you are given in the exam for the exact commands.
1 markWrite mode1CP2 Paper 2 style

A file called scores.csv already exists. What happens when a program opens it with mode "w"?

A New data is added to the end of the file
B The old contents are erased and writing starts again
C The program stops with an error
D Nothing changes until the file is closed
4 marksRead a file1CP2 Paper 2 style

Write a Python program that reads every name from names.txt (one name per line) and prints each name with its line number (1, 2, 3...). (4 marks)

Hint: Open for reading, set a counter, loop through the lines, print, add 1, close.
+40 XP
1 markAppend mode1CP2 Paper 2 style

Which mode adds new data to the end of an existing file without deleting what is already there?

A "r"
B "w"
C "a"
D "c"
4 marksFind and fix the errors1CP2 Paper 2 style

This program should add up the scores in data.csv (each line is name,score). It has two errors. Identify each error and write the corrected program. (4 marks)

file = open("data.csv", "r")
for line in file:
    fields = line.split(",")
    total = total + fields[1]
file.close()
print(total)
Hint: What does total hold the first time through the loop? What type is fields[1]?
+40 XP
3 marksSplit a CSV line1CP2 Paper 2 style

Each line of people.csv looks like Ava,15 followed by a newline. The line has been read into the variable line. Write Python that stores the name in a variable called name and the age, as a number, in a variable called age. (3 marks)

Hint: Remove the newline, split at the comma, then convert the age.
+30 XP
1 markClosing files1CP2 Paper 2 style

Why must a program close a file when it has finished with it?

A To stop other programs from ever reading the data
B To make sure the data is saved and the file is released
C Because files close automatically when the program ends, so closing is optional
D To delete the file from memory
Quick recall flashcards

Module complete! 🎉

Score loading...

⚡ +10 XP