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.
ExamplePython:
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.