Open, Read, Write, Close & Data Persistence.
To free up memory/resources, save data physically to disk, or prevent file corruption/locks.
Output: 100100
Reason: Data read from file is a String. + concatenates instead of adding.
(a) Fix: newPrice = float(price) * 1.2 (Must cast string to float).
(b) Syntax: endOfFile() usually needs brackets in ERL methods.
data.txt: 5, 2, 8.
478: x = 0 479: while NOT f.endOfFile(): 480: val = int(f.readLine()) 481: if val > 4: x = x + val 482: else: x = x - val 483: print(x)
Trace Table:
| val | x | Output |
|---|---|---|
maths_scores.txt.
pass_list.txt.
527: f1 = open("maths_scores.txt")
528: f2 = newFile("pass_list.txt")
529: while NOT f1.endOfFile()
530: line = f1.readLine()
531: score = int(line)
532: if score >= 50:
533: f2.writeLine(line)
534: f1.close()
535: f2.close()
(a) "Write" mode creates a new file / overwrites existing data.
(b) open("diary.txt", "a") (Append mode).
if exists("maths_scores.txt") then ...
OR TRY ... EXCEPT block.