Computer Science · Theme B: Computational thinking and problem-solving
B2.5 — File processing
Computer Science · SL / HL · syllabus-mapped notes
CS_B2.5.1
File-processing operations
Opening text files in read, write and append modes, then reading, writing and closing.
Full note — freeYou must be able to construct code that performs file-processing operations on text files: opening a file, reading from or writing to it, and closing it. File modes read ("r"): read existing contents. write ("w"): create or overwrite the file. append ("a"): add new data to the end, keeping what is already there. Python functions (may include) open() opens a file and returns a file object; read() reads the whole file; readline() reads one line; write() writes text; close() closes the file. (Illustrative, not a closed set.) e.g. write then append then read f = open("log.txt", "w") # write mode f.write("line 1\n") f.close() f = open("log.txt", "a") # append mode f.write("line 2\n") f.close() f = open("log.txt", "r") # read mode print(f.read()) f.close() Java classes (may include) Scanner reads input from a file; BufferedReader reads text efficiently line by line; FileWriter writes text to a file. (Illustrative, not a closed set.) Always close a file when operations are complete (or use a construct that closes it for you). Opening in write mode "w" erases the existing contents, so use append "a" to keep them.
