2.2.1 - Files and persistent records
A file lets records survive after a program finishes. You will read complete text files, distinguish a blank line from the end of a file, write a new result safely, and put file processing behind a clear function interface. OCR pseudocode and Python express these operations differently.
A file and an open file handle have different lifetimes
A file stores data outside a program's working variables; an open file handle is the program's current connection to that file. Opening for reading starts a read position at the beginning. Each line read advances that position. Opening the same file again creates a new reading session starting at the beginning; it does not resume the old position automatically.
Suppose visits.txt contains three lines, in this order:
4
0
7
The lines are text. To add their numerical values, the program must convert each line to an integer. The filename, record format and treatment of errors belong in the input contract: here, every line is a valid non-negative integer, with no header or blank records.
OCR's notation opens the file with openRead, reads one line with the handle's readLine method, and releases the connection with close:
visits = openRead("visits.txt")
first = visits.readLine()
visits.close()
print(first)
The first record is 4. Closing the handle does not delete the file. Reading one line does not remove that record either. A later program may read the same stored data. In a normal local filesystem that is persistence across program runs; a browser exercise's workspace lifetime is a separate platform rule. In this course, supplied files start fresh for each Run. A write followed by a read within one run can be tested; do not rely on changes surviving a later Run.
Read each record once and stop at the end of the file
End of file, or EOF, means no unread data remains. It is a condition of the reading session, not a special record that should be added to the total. OCR supplies endOfFile() so that a loop can check before reading:
function totalVisits(filename)
total = 0
visits = openRead(filename)
while NOT visits.endOfFile()
total = total + int(visits.readLine())
endwhile
visits.close()
return total
endfunction
print(totalVisits("visits.txt")) // outputs 11
For the three records, the totals after successive reads are 4, 4 and 11. An empty file performs zero iterations and returns 0. Reading outside the loop first and then reading again inside it can accidentally discard the first record. A loop also needs an advancing read; repeatedly testing EOF without consuming data may never terminate.
Python's readline() returns a string which normally includes the line-ending character. It returns "" at EOF. A blank line returns "\n", so blank data and EOF are different. A final record without a newline still returns its text before a later read returns "". For the following example, names.txt contains Mia followed by a newline, a blank line, then Noor without a final newline. The program displays Mia, an empty line and Noor.
with open("names.txt", "r", encoding="utf-8") as source:
line = source.readline()
while line != "":
print(line.rstrip("\n"))
line = source.readline()
rstrip("\n") removes a line ending for display; it is performed after the EOF decision. Testing line.strip() != "" instead would wrongly stop on a blank record. For reading every line, for line in source: is simpler: file iteration already stops at EOF. Neither Python form is OCR's endOfFile() method. Use OCR pseudocode in a labelled source editor or suitable local tool; the Python runner executes Python only.
Test the original Python read result for "" before removing whitespace. A blank line is "\n" and is still data; an empty file reaches EOF without returning any record.
Writing a file replaces or extends stored content
Opening a file for writing can destroy its previous contents before the first new record is written. OCR's openWrite overwrites the previous content. Its writeLine adds a line of text to the output file:
report = openWrite("report.txt")
report.writeLine("Day 1: 11")
report.writeLine("Day 2: 9")
report.close()
The finished report contains two lines, regardless of any older report. The names openRead and openWrite describe different access intentions; do not open an input file for writing when you mean to inspect it.
In Python, mode "w" creates or truncates a file; "a" appends at the end without discarding existing contents. Python's write() does not add a newline automatically. To create two distinct lines, supply "\n" yourself:
with open("report.txt", "w", encoding="utf-8") as report:
report.write("Day 1: 11\n")
report.write("Day 2: 9\n")
with open("report.txt", "r", encoding="utf-8") as report:
print(report.read(), end="")
Replacement report
Example runDay 1: 11
Day 2: 9
This writes and reopens the file within one execution. It does not establish cross-Run persistence. If a task requires replacement, appending is an error even when a fresh empty test file hides it. Starting with an existing report is therefore a useful adverse case. In a local application, write valuable replacements to a separate file and check them before replacing the original; simply opening the only original in "w" is destructive.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account