Knowledge organisersAdditional Programming Techniques
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.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()