The answersDownload the PDF
Worksheet

F7.1 Reading and writing files

Files and databases · GCSE · OCR J277 2.2.3, Edexcel 1CP2 6.4.2 · about 15 min

BugBotLab
NameClassDate

What this lesson is about

Open, read, write, append and close: a run log in a CSV file.

Questions 6 marks in all

  1. [1 mark]Put the steps for reading a file in order.

    Number the lines 1 to 3 to put them in the right order.

    1. Open the file
    2. Read from the file
    3. Close the file
  2. [1 mark]What does opening a file with mode "w" do to a file that already exists?

    1. AEmpties it before writing
    2. BAdds to the end of it
    3. CReads it
    4. DNothing until close is called
  3. [1 mark]Which mode adds new lines to the end of a file and keeps what was there?

    1. A"a"
    2. B"w"
    3. C"r"
    4. D"x"
  4. [1 mark]What does this program print?

    line = "3,square,80,9.4\n"
    fields = line.strip().split(",")
    print(fields[1], float(fields[2]) + 1)
  5. [1 mark]Why use with open(...) as f:?

    1. AThe file is closed automatically at the end of the block
    2. BIt reads the file faster
    3. CIt makes the file bigger
    4. DIt is the only way to write
  6. [1 mark]Why store data in a file rather than only in variables?

    1. AVariables are lost when the program stops; a file keeps the data
    2. BFiles are faster than variables
    3. CVariables cannot hold numbers
    4. DFiles cannot be changed

The task: log the run

Drive forward 25 cm, timing it with clock(). Then append a line to runs.csv for this run: run number 4, task wall, 25 cm, and the seconds rounded to one decimal place, in the same format as the other lines. Finally read the file and print 4 runs logged, counting the lines after the header rather than typing 4. The task starts from the original four-line runs.csv every time it runs, whatever earlier runs added to the copy above.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

start = clock()
forward(50, distance=25)

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/f7-1-reading-and-writing-files/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. Write a program that prints the total distance of all the runs in the file.
  2. Log a whole session: drive three different distances, appending a line for each.
  3. What happens to runs.csv if you use mode "w" instead of "a"? Try it, then reset the file.