Use Python's open() function or Java's file-stream classes to access a file, then read from or write to it before closing it. A Python context manager or Java try-with-resources statement is preferred because it closes the file automatically.
The File-Processing Mechanism
In file processing, a program normally follows four steps: open the file, process its contents, write data if required, and close the file. Closing releases the operating system resource and ensures buffered output is saved.
| Operation | Python | Java |
|---|---|---|
| Open for reading | open("data.txt", "r") | new BufferedReader(new FileReader("data.txt")) |
| Read | read(), readline(), or iteration | readLine() |
| Open for writing | open("output.txt", "w") | new BufferedWriter(new FileWriter("output.txt")) |
| Write | write() | write() |
| Close safely | with closes automatically | try-with-resources closes automatically |
Python Example
with open("data.txt", "r") as input_file:
contents = input_file.read()
with open("output.txt", "w") as output_file:
output_file.write(contents)
The mode "r" means read, while "w" means write and replaces existing contents. The mode "a" means append, adding data at the end. Without with, the programmer must call input_file.close() or output_file.close() explicitly.
Java Example
try (BufferedReader reader = new BufferedReader(
new FileReader("data.txt"));
BufferedWriter writer = new BufferedWriter(
new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
System.out.println("File error");
}
Here, null indicates the end of file. IOException handles problems such as a missing file or failed write operation.
IB Exam Technique
For B2.5 File processing, trace the sequence open, read/write, close and identify the file mode. A common misconception is that writing automatically preserves existing data: write mode usually overwrites it, whereas append mode preserves it and adds new data.