Introduction to File Processing
Programs often need to store data beyond the lifetime of a single run , saving scores, logging events, reading configuration, or storing records. This is where file processing comes in.
Unlike variables (which live only in RAM and disappear when the program ends), files persist on disk. File-processing operations allow your program to:
- Read data that was previously saved
- Write new data to disk
- Append additional data to an existing file
File Processing: The set of operations (open, read, write, append, close) that allow a program to interact with files stored on a disk or other persistent storage medium.
Before any of these operations can happen, a file must be opened , this creates a connection (called a file handle or stream) between your program and the file on disk.
Think of a file like a physical notebook. Before you can read or write in it, you have to pick it up and open it. When you're done, you close it and put it back on the shelf , leaving the content intact for next time.
Opening a File , Modes
When opening a file, you must specify a mode that tells the program what you intend to do with it. The three core modes are:
| Mode | Symbol | Behaviour |
|---|---|---|
| Read | r | Opens an existing file for reading. File must already exist. |
| Write | w | Creates a new file, or overwrites an existing one. |
| Append | a | Opens a file and adds data to the end. Creates the file if it doesn't exist. |
File Mode: A parameter specified when opening a file that determines whether the program can read from it, write to it, or append to it.
Opening a file in Python:
open("data.txt", "r") # read mode
open("data.txt", "w") # write mode (creates or overwrites)
open("data.txt", "a") # append mode
Opening a file in Java (read mode using Scanner):
Scanner sc = new Scanner(new File("data.txt"));
Java uses class-based streams, so the mode is implied by which class you use (Scanner for reading, FileWriter for writing).
Using "w" when you meant "a" is a critical mistake , "w" silently deletes all existing content in the file before writing. Always double-check your mode.
