ProceduralOCR J277
DashboardCoursePracticeReviewProgressGlossary
Saved on this deviceContinue learning

Procedural · OCR J277 programming practice

Progress stays in this browser unless you export it.

Course/Robust programs/Reading and writing files
J277 · 2.2.3

Unit 10 · Lesson 6

Reading and writing files

Lesson progress0 / 7

Build the idea

Start with the concept and its key vocabulary.

Key idea

Use OCR ERL file operations and their Python equivalents to write and read text safely.

A file stores data beyond the current program run. It must be opened before reading or writing and closed afterwards. ERL uses open, readLine, writeLine, close, endOfFile and newFile. Python opens a file with a mode: 'r' reads and 'w' writes a new or replaced file. Python write does not automatically add a line break, so add \n when a complete line is required.

File

A named collection of data stored outside the program's variables.

Open

Prepare a file for reading or writing and obtain a file handle.

File handle

The program value used to access an open file.

End of file

The position after the final item in a file.

Keep these in mind

  • ERL: myFile = open(filename), then myFile.readLine() or myFile.writeLine(data).
  • ERL newFile(filename) creates a new empty file.
  • myFile.endOfFile() supports a loop that reads until no lines remain.
  • Python mode r reads; mode w creates or overwrites for writing.
  • Close the file when finished so buffered changes are saved.
  • A file procedure should use its data and filename parameters instead of asking for replacement input.

Learning objective

Use OCR ERL file operations and their Python equivalents to write and read text safely.

Exam tip

In a SaveLogs(data, filename) procedure, use both supplied parameters: open filename, write data, then close the handle.

Common mistake

Do not forget close(). Also remember Python's write() needs \n when separate lines are required, whereas ERL writeLine writes a line.

PreviousNext