Proof Academy · Python · Journey 09

Files, CSV and persistent data

Read records from a text file, handle incomplete rows and write a report that can be reopened.

Lab and core lesson: 45–55 minutes, plus guided study · Builds on Searching and sorting

01 · Understand and predict

Follow data from a file to a report

An open file connects your program to stored data. Mode r reads, w creates or replaces, and a adds to the end. A with block closes the file when the block ends, even if an exception occurs inside it.

CSV means comma-separated values. These exercises use a simple subset with no header and no quoted fields, so split(',') is enough. For general CSV with quoted commas, use Python’s csv module. Check that the row has the expected number of fields before accessing them.

with open("points.csv", "w", encoding="utf-8") as source:
    source.write("A12,4\nB17,6\n")

total = 0
with open("points.csv", "r", encoding="utf-8") as source:
    for line in source:
        team, text = line.strip().split(",")
        total = total + int(text)
print(total)

Worked trace

  1. The first block creates a file containing two rows. Each newline starts a new record.
  2. Reading the first row gives A12 and the text '4'. int converts '4' to the number 4.
  3. The second row adds 6. The file closes at the end of the block and the program prints 10.
Which mode should an end-of-day report use when it must contain only the latest totals?

From code to machine. An open file has a path and a position. The operating system or browser runtime manages that file, while the values you compute are held in working memory. This lab provides a temporary virtual filesystem. On a computer, saving the report to secondary storage lets you reopen it after the program ends.

Guided study

Read it, trace it, test it

Understand the file contract

A text file stores characters. A newline ends a row in this exercise and a comma separates fields. For A12,4, the team code remains text and the points field is converted after validation. Decide in advance whether the file has a header, how many fields are expected, and whether spaces should be stripped. These lessons use headerless files without quoted fields. A real CSV can contain quoted commas, so a general parser must handle those rules rather than blindly splitting every comma.

The file path is part of the program's input. On a computer, open("points.csv") looks in the current working directory. An IDE may use the project folder or a configured working directory. If Python reports FileNotFoundError, check the actual filename, including the extension, and the folder the program is running from. In the browser lab the starter creates the file in the virtual workspace. Downloaded files must be placed alongside each other for the local practice task, or opened with the correct path.

Trace a report safely

Raw rowAfter splitValid?Report row
A , 06A and 06 after trimmingYesA,6
B,B and empty textNoNo row
C,7,extraThree fieldsNoNo row
D,21D and 21No, rangeNo row

Check len(fields) before accessing a field by index. Remove surrounding whitespace from each field where the brief permits it. Reject an empty identifier. For points, test .isdecimal() before int(), then compare the integer with the limit. When writing the result, use the cleaned identifier and the converted number to produce the required format. A newline written after each record ensures that the next one starts on a separate line.

Choose the correct mode and scope

Use read mode when you want to inspect existing data. Use write mode for a replacement report. It clears the old content immediately on opening, so give input and output different filenames. Append mode is for a growing log, where previous entries should stay. A task that says “produce today's report” and a task that says “add this record to the history” often need different modes.

A with block closes the file when control leaves the block. Open the output once, outside the processing loop. Opening it in write mode on every pass would repeatedly clear the earlier accepted rows. Opening it only inside an if that detects a valid row can leave yesterday's report untouched when today's input has no valid rows. A strong test checks two successive runs, including one that should produce an empty output file.

In the browser, the Test input first supplies the row count and then the raw rows. The starter writes them into the named CSV. The rest of your program should read from that file. Run with my input lets you try a particular malformed row before running the full set. The output check shows what was read back from the generated report. In a local IDE, open the saved report itself as well. The output panel alone cannot tell you which file was written.

Practise a Paper 2 change request

A provided stock.csv contains one item code and a quantity per line. Create a new restock.csv with the codes of items whose quantity is below 4. A valid row has a non-empty code and a whole-number quantity of 0 or more. Preserve input order. Use a file with rows A,0, B,4, C,3, D,broken and E. Predict the contents of the report, including whether there should be a line for B. Then test an empty input file and a file that contains only invalid rows.

Check your guided practice

The report contains A and C, each on its own line. B is at 4, which does not satisfy “below 4”. D fails the digit check and E fails the field count. Open the output in write mode before processing the rows so empty and all-invalid files both leave an empty report. Keep your input file untouched and use a new output name.

02 · Run and repair

Replace yesterday’s report

The setup writes a stale record. The program must replace that record with the new code and then reopen the file. Try B04 and repair the mode used to write today’s report.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Change the second open call to write mode. Leave the setup and read-back blocks unchanged.

03 · Build independently

Filter a points file

The starter creates points.csv from the test input. Keep that setup, then read the file and write a clean report.csv. The browser checks the content you read back and print.

  • Each record should have exactly two fields: a non-empty team code and a points value of 0–20. Strip surrounding spaces from each field. Accept decimal digits only for points.
  • Ignore incomplete or invalid rows. Keep the order of accepted rows. Write each clean code and canonical integer with a comma between them.
  • Open the report in write mode even if no rows are valid. Then reopen it and print the contents using print(report.read(), end='').

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Open both files with a with block. Use len(fields) to guard access to the two fields. Check isdecimal() before converting the value.

04 · Explain and transfer

Explain your reasoning

What should happen to an old report when the new file has no valid rows?

Compare your explanation

The report should become empty. Open it in write mode before the processing loop so the old data is cleared even when no row is accepted.

Independent follow-up. Download your Python file and run it in a local IDE with the same inputs. Reopen report.csv outside the program. Add a test in which all the rows are invalid and confirm the old output is cleared.

Original GCSE practice · Pearson Edexcel 1CP2 1.2.2, 3.1.2, 3.2.1, 6.4.2–6.4.3. Download your .py file to keep it after leaving the page.

Next: Binary and text encoding →