File-Processing Operations
Opening a File
- Files must be opened before use.
- Modes:
- Read (r) → Reads data from a file (must exist).
- Write (w) → Creates or overwrites a file.
- Append (a) → Adds data to the end of a file.
Python:
open("data.txt", "r")Java:
Scanner sc = new Scanner(new File("data.txt"))Using "w" when you mean "a" → existing data is lost.
Reading from a File
Methods to read:
- Entire file (read() in Python).
- Line by line (readline() / loop in Python, nextLine() in Java).
Python:
with open("data.txt", "r") as f:
for line in f:
print(line.strip())Java:
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}Forgetting to check if file exists → causes crash.
Writing to a File
Overwrites by default in write mode.
Python:
with open("data.txt", "w") as f:
f.write("Hello World\n")Java:
FileWriter fw = new FileWriter("data.txt");
fw.write("Hello World\n");
fw.close();Use "w" for new files or fresh data.
Forgetting close() in Java → data may not save.
Appending to a File
Adds new data without deleting old content.
Python:
with open("data.txt", "a") as f:
f.write("New entry\n")Java:
FileWriter fw = new FileWriter("data.txt", true);
fw.write("New entry\n");
fw.close();Closing Files
- Releases resources and ensures data is saved.
- Python: with auto-closes files.
- Java: Must call .close() explicitly.
Always close files (or use auto-close features)
Assuming file auto-closes in Java → memory leaks possible.
Error Handling in File Processing
- Files may not exist, or permission may be denied.
- Handle with exceptions:
Python:
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found!")Java:
try {
Scanner sc = new Scanner(new File("missing.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}Always add error handling for robustness.
Ignoring errors → program crashes in real use.
Be ready to:
- Show file input/output with correct modes.
- Write small programs that read, write, and append.
- Include error handling (FileNotFound, IOError).