File-Processing
What Is File Processing?
File processing allows programs to store and retrieve data from external files.
Files can be opened in different modes: read, write, and append.
File Handling Functions in Python and Java
| Operation | Python Function | Java Class/Method |
|---|---|---|
| Open a file | open("file.txt", "r") |
new FileReader("file.txt") |
| Read from file | file.read(), file.readline() |
BufferedReader.readLine() |
| Write to file | file.write("text") |
FileWriter.write("text") |
| Append data | open("file.txt", "a") |
new FileWriter("file.txt", true) |
| Close file | file.close() (or implicit with with) |
close() on BufferedReader or FileWriter |
Visualising File Modes
Imagine you have a text file, example.txt, containing three items.
In a “line‐delimited” file each item sits on its own line; in a “CSV” file they share one line, separated by commas.
Line-Delimited File (1D array)
Initial Content
Beta
Gamma
After Write Mode (w)
After Append Mode (a)
Beta
Gamma
Delta
CSV-Delimited File (1D array)
Initial Content
After Write Mode (w)
After Append Mode (a)
2D-Array File Content
Now imagine each line in example.txt is a “record” (an object),
with comma-separated fields. Together they form a 2D array: rows of records, columns of fields.
Initial Content
A2,B2,C2
After Write Mode (w)
D4,D5,D6
After Append Mode (a)
A2,B2,C2
D1,D2,D3
D4,D5,D6
Examples
For the following code samples, feel free to use either of the following files:
Example: Reading a 2D Array (CSV)
import csv
# Read CSV rows into a list of lists
with open("example.txt", "r") as f:
reader = csv.reader(f)
data = [row for row in reader]
print("2D Data:", data)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Read2DExample {
public static void main(String[] args) {
List<String[]> data = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
data.add(line.split(","));
}
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
System.out.println("2D Data: " + data);
}
}
Example: Writing a 2D Array (CSV)
import csv
# Sample 2D data
data = [["A1","B1","C1"], ["A2","B2","C2"]]
# Write rows to CSV (overwrite)
with open("example.txt", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
import java.io.FileWriter;
import java.io.IOException;
public class Write2DExample {
public static void main(String[] args) {
String[][] data = { {"D1","D2","D3"}, {"D4","D5","D6"} };
try (FileWriter fw = new FileWriter("example.txt")) {
for (String[] row : data) {
fw.write(String.join(",", row) + "\n");
}
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
}
}
Example: Appending a 2D Array (CSV)
import csv
# New rows to append
new_rows = [["E1","E2","E3"], ["E4","E5","E6"]]
# Append rows to CSV
with open("example.txt", "a", newline="") as f:
writer = csv.writer(f)
writer.writerows(new_rows)
import java.io.FileWriter;
import java.io.IOException;
public class Append2DExample {
public static void main(String[] args) {
String[][] newRows = { {"E1","E2","E3"}, {"E4","E5","E6"} };
try (FileWriter fw = new FileWriter("example.txt", true)) {
for (String[] row : newRows) {
fw.write(String.join(",", row) + "\n");
}
} catch (IOException e) {
System.out.println("Append error: " + e.getMessage());
}
}
}
Avoiding Common File Handling Errors
- File Not Found:
Before reading, check existence with
os.path.exists()in Python orFile.exists()in Java. Handle missing files inexcept/catchblocks. - Permission Errors:
Ensure your program has read/write permissions. In Python, catch
PermissionError; in Java, catchIOExceptionand inspecte.getMessage(). - Forgetting to Close Files:
Use Python’s
withcontext manager or Java’s try-with-resources to auto-close. This prevents resource leaks and file locks.
Key Takeaways
- File processing lets you read, write, and append data to external files.
- Python uses
open(),read(),write(), and context managers; Java usesFileReader,BufferedReader, andFileWriter. - Always handle missing files and permissions with proper exception handling.
- Use context managers (Python) or try-with-resources (Java) to ensure files are closed and resources freed.