The use of basic file handling operations: Open, Read, Write, Close
2.2.3 Additional Programming Techniques
Practise exam questionsAdditional Programming Techniques — Note 3 of 12
why you need to open and close a file as well as complete the techniques listed.
File handling allows programs to read data from and write data to external files. Files must be opened before they can be used and closed afterwards to ensure changes are saved. Files can be opened in read mode (to access existing data) or write mode (to save new data). This is essential for storing data permanently between program runs.
myFile = open("sample.txt") in OCR pseudocode.myFile.readLine() returns the next line in the file.myFile = open("sample.txt") then myFile.writeLine("text").myFile.close() ensures all changes are saved.endOfFile() checks if the end of the file has been reached (useful in loops).newFile("name.txt") creates a new empty file."r" opens a file for reading; "w" creates a new file or OVERWRITES an existing one.open("f.txt") → open("f.txt", "r"); readLine() → readline(); writeLine(x) → write(x + "\n"); endOfFile() → line == ""; newFile("f.txt") → open("f.txt", "w").readline() returns an empty string "" when there are no lines left, so while line != "": repeats until the end of the file."w" wipes everything already in it.procedure SaveLogs(data, filename) → open(filename), writeLine(data), close(). Must use the parameters passed in.# Writing to a file
f = open("scores.txt", "w")
f.write("Alice,85\n")
f.write("Bob,92\n")
f.close()
# Reading from a file
f = open("scores.txt", "r")
for line in f:
print(line.strip())
f.close()file = open("data.txt", "w") # "w" creates the file, or overwrites it
file.write("Line 1\n") # \n moves on to a new line
file.write("Line 2\n")
file.close() # always close the file to save itfile = open("data.txt", "r") # "r" opens the file for reading
line = file.readline() # read the first line
while line != "": # readline() returns "" at the end of the file
print(line.strip()) # strip() removes the newline at the end
line = file.readline() # read the next line
file.close()Ready to test yourself?
Practise 2.2.3 questions