Learning route
Read a record. Convert its fields. Write a report you can verify.
Prerequisite: Can loop over a list, split a string and convert numeric text. Can distinguish a return value from screen output.
- Choose read, write or append mode to match a requirement.
- Process simple comma-separated records one line at a time.
- Convert numeric fields before calculating.
- Write a reproducible report and test a second run and an empty file.
Retrieve and explain
- What does
"Asha,7".split(",")produce? - What is the type of "7" before int() is applied?
- What does a counter do in a loop?
- Why might an on-screen result be insufficient if the program is closed?
A file keeps data beyond the lifetime of the running program. A file handle lets the program read or write that file. Relative filenames are resolved from the program’s working directory, which an IDE may set differently from the script’s folder.
| Mode | Purpose | Existing content |
|---|---|---|
| "r" | Read an existing file | Retained; opening a missing file raises FileNotFoundError. |
| "w" | Create a fresh output | Replaced when opened; use for a regenerated report. |
| "a" | Add to an existing log | Retained; new data is added at the end. |
data_file = open("scores.csv", "r")
for line in data_file:
fields = line.strip().split(",")
name = fields[0]
score = int(fields[1])
print(name, score)
data_file.close()
For a line Asha,7 , strip removes its surrounding whitespace, including the line ending. split creates two string fields. Convert the numeric field before arithmetic.
report = open("summary.txt", "w")
report.write("Total: 12\n")
report.close()
write() needs a string and does not automatically add a new line. Use str() for numbers and "\n" for a line ending. Close the handle after processing. Python’s with open(...) is another valid way to ensure closure; these examples use explicit open/close to make the lifecycle visible.
Simple CSV has stated assumptions.
Our files contain a name and an integer, separated by one comma. No names contain commas or quotes. General CSV may contain quoted commas and embedded newlines; use a proper CSV parser for that broader format. Malformed records and missing files are outside today’s build requirements.
Worked example
The file scores.csv contains the three records below. Read every record, add the numeric scores, then replace a summary file. The output uses two lines.
Asha,7
Ben,5
Cara,0
total = 0
count = 0
data_file = open("scores.csv", "r")
for line in data_file:
fields = line.strip().split(",")
score = int(fields[1])
total = total + score
count = count + 1
data_file.close()
report = open("summary.txt", "w")
report.write("Count: " + str(count) + "\n")
report.write("Total: " + str(total) + "\n")
report.close()
| Record processed | count | total |
|---|---|---|
| None yet | 0 | 0 |
| Asha,7 | 1 | 7 |
| Ben,5 | 2 | 12 |
| Cara,0 | 3 | 12 |
The file summary.txt contains Count: 3 and Total: 12 on separate lines. A zero score still counts as a record. An empty input file gives Count: 0 and Total: 0.
Repair practice
The program should read values and create a fresh two-line report. It currently joins numeric text instead of adding numbers, and repeated runs duplicate the report. Repair those faults.
total = "0"
data_file = open("scores.csv", "r")
for line in data_file:
fields = line.strip().split(",")
total = total + fields[1]
data_file.close()
report = open("summary.txt", "a")
report.write("Total: " + total + "\n")
report.write("Complete\n")
report.close()
Use the worked-example records. Explain why "0" + "7" is not numeric addition. Then explain why append mode is wrong for this report but can be right for a log.
Repair feedback
total = 0
data_file = open("scores.csv", "r")
for line in data_file:
fields = line.strip().split(",")
total = total + int(fields[1])
data_file.close()
report = open("summary.txt", "w")
report.write("Total: " + str(total) + "\n")
report.write("Complete\n")
report.close()
The original produces the text 0750, not 12. Integer initialisation and conversion fix the calculation; str(total) enables text output. Write mode regenerates the two-line report. Append mode would be suitable for preserving earlier log entries when that is the requirement.
Independent practice
Independent build: stock reorder report. Download stock.csv. Each line contains an item name and a non-negative integer quantity. There is no header, no blank line and no comma within a name.
- Read every line and convert its quantity to an integer.
- For quantities below 5, write the uppercase name and quantity, separated by a comma, to
reorder.csv. Put each matching record on its own line. - Regenerate the report on each run rather than appending.
- Count all input records and matching records. Display Read: and Reorder: counts.
- Test the supplied file, run it twice, then use an empty file and the all-sufficient-stock file.
The report has no header. A quantity of exactly 5 is sufficient. Keep the input file unchanged. Make a copy of a test file and name the copy stock.csv in a separate test folder when switching cases.
# Proof Academy | Lesson 06 | Stock reorder report
# Put stock.csv in the Python working directory.
# Format: item,quantity (no header; valid integers; no embedded commas).
INPUT_FILE = "stock.csv"
OUTPUT_FILE = "reorder.csv"
read_count = 0
reorder_count = 0
# Your task: open input for reading and output for a fresh report.
# Your task: split each line, convert quantity and count input records.
# Your task: for quantity < 5, write uppercase item,quantity plus newline.
# Your task: close both files and display Read and Reorder counts.
Model program and marking guidance
# Proof Academy | Lesson 06 | Worked solution
INPUT_FILE = "stock.csv"
OUTPUT_FILE = "reorder.csv"
read_count = 0
reorder_count = 0
data_file = open(INPUT_FILE, "r")
report = open(OUTPUT_FILE, "w")
for line in data_file:
fields = line.strip().split(",")
item = fields[0]
quantity = int(fields[1])
read_count = read_count + 1
if quantity < 5:
report.write(item.upper() + "," + str(quantity) + "\n")
reorder_count = reorder_count + 1
data_file.close()
report.close()
print("Read:", read_count)
print("Reorder:", reorder_count)
- Opens input in read mode and a fresh output in write mode. [1]
- Processes every line, splits fields and converts quantity. [1]
- Counts every input record, including records not selected. [1]
- Selects quantity < 5 and counts only selected records. [1]
- Writes uppercase name and numeric quantity as two comma-separated fields. [1]
- Writes one selected record per line; no added header or blank records. [1]
- Closes both files after processing and displays accurate labelled counts. [1]
- Checks supplied, repeated-run, empty and all-sufficient cases, including output-file contents. [1]
Exam practice
Original Proof Academy practice · 6 marks. A script regenerates a class report from simple CSV input.
- Choose the mode for reading the existing input. [1]
- Choose the output mode that replaces yesterday’s report. [1]
- State the type of each element returned by
"Asha,12".split(","). [1] - Write the expression converting the second field of
fieldsto an integer. [1] - Explain why
write("Asha")followed bywrite("Ben")puts both names together, and give a repair. [2]
Worked feedback
"r" (1); "w" (1); string (1); int(fields[1]) (1). write does not add line endings automatically (1); include "\n" after each name (1). Accept an equivalent repair that writes one name on each line.
Homework and feedback
30 minutes: 5 minutes planning, 15 minutes coding, 10 minutes repeat-run and edge-case tests.
Using the same stock.csv format, generate restock.csv. For each quantity below 5, write the uppercase name and the number needed to reach 5. Display Units to order: and the combined number. Test the supplied file and an empty file. The report should be replaced on each run.
Homework feedback
units = 0
data_file = open("stock.csv", "r")
report = open("restock.csv", "w")
for line in data_file:
fields = line.strip().split(",")
quantity = int(fields[1])
if quantity < 5:
needed = 5 - quantity
units = units + needed
report.write(fields[0].upper() + "," + str(needed) + "\n")
data_file.close()
report.close()
print("Units to order:", units)
Supplied data → PENCILS,1 and ERASERS,5 on separate lines; Units to order: 6. Empty input → empty output and Units to order: 0. Check that the source data is unchanged and the second run does not duplicate output.
Sources and further practice
This chapter is written for Pearson Edexcel GCSE Computer Science 1CP2. Use the specification references in the chapter heading to locate the relevant requirements. Practice questions and point allocations on this page are original Proof Academy teaching material unless a question is explicitly identified as a sourced past-paper bridge.
- Pearson Edexcel 1CP2 specification
- PMT Paper 1 papers and mark schemes
- PMT Paper 2 papers and mark schemes
When using an original paper, open its matching mark scheme and supplied coding files where required. Use that paper's instructions and marks. A short classroom exercise is not a substitute for a full official task.
Trace lab · inline, no inner scroll
CSV score report
Asha,7 · Ben,5 · Cara,0. A zero score still counts as a record.
Keep your evidence
Export your notes before changing devices.
Notes stay in this browser. The Quiz tab records the chapter check, and Resources holds the long-answer questions.