File Handling
Persist data beyond the life of a program by reading from and writing to files. Understand open modes, sequential access and the importance of closing files.
Every time you save a document, edit a spreadsheet or export a photo, a program is writing data to a file. Without file handling, every program would start fresh each time it ran - no saved games, no stored contacts, no history.
r), write (w), or append (a).Opening, Reading and Writing
Before you can interact with a file you must open it. The open mode determines what operations are permitted and where the file pointer starts.
r - Readw - Writea - Append# --- Write a file --- with open("scores.txt", "w") as f: f.write("Alice 95\n") f.write("Bob 82\n") # File is automatically closed here # --- Read the whole file --- with open("scores.txt", "r") as f: contents = f.read() print(contents) # --- Read line by line --- with open("scores.txt", "r") as f: for line in f: print(line.strip()) # --- Append a new score --- with open("scores.txt", "a") as f: f.write("Carol 78\n")
using System.IO; // --- Write a file --- File.WriteAllText("scores.txt", "Alice 95\nBob 82\n"); // --- Read the whole file --- string contents = File.ReadAllText("scores.txt"); Console.WriteLine(contents); // --- Read line by line --- string[] lines = File.ReadAllLines("scores.txt"); foreach (string line in lines) Console.WriteLine(line); // --- Append a new score --- File.AppendAllText("scores.txt", "Carol 78\n");
Python's with statement automatically closes the file when the block ends. In C#, File.* helper methods handle opening and closing for you. If you open a file manually, always call close() / Close() - unflushed buffers can mean data is silently lost.
Reading Methods Compared
There are several ways to read from a file, each suited to a different situation:
Python methods
read()readline()readlines()C# equivalents
ReadAllText()StreamReader.ReadLine()ReadAllLines()with open("data.txt", "r") as f: all_lines = f.readlines() # list of strings for line in all_lines: parts = line.strip().split(",") # split CSV name = parts[0] score = int(parts[1])
string[] allLines = File.ReadAllLines("data.txt"); foreach (string line in allLines) { string[] parts = line.Split(','); string name = parts[0]; int score = int.Parse(parts[1]); }
High Score Table
A common exam scenario: read scores from a file, find the highest, then add a new score and save the file.
# Read existing scores scores = [] with open("scores.txt", "r") as f: for line in f: scores.append(int(line.strip())) highest = max(scores) print(f"Highest score: {highest}") # Add new score new_score = int(input("Enter your score: ")) with open("scores.txt", "a") as f: f.write(str(new_score) + "\n") print("Score saved!")
// Read existing scores int[] scores = Array.ConvertAll( File.ReadAllLines("scores.txt"), int.Parse); Console.WriteLine($"Highest score: {scores.Max()}"); // Add new score Console.Write("Enter your score: "); string newScore = Console.ReadLine(); File.AppendAllText("scores.txt", newScore + "\n"); Console.WriteLine("Score saved!");
Simulated File I/O Sandbox
Experiment with the three file modes. The virtual disk shows you exactly what is stored after each operation.
Three Quick Challenges
A file log.txt already contains Line 1. After running this code, how many lines does the file contain?
with open("log.txt", "w") as f: f.write("Line 2 ")
You want to add a new score without deleting existing scores. Which mode?
This crashes at runtime. Why?
f = open("data.txt", "r") f.write("hello") f.close()
Check Your Understanding
"w"). The file already contains data. What happens to the existing data?w) truncates (empties) the file before writing. Use append mode (a) to preserve existing content.a) moves the file pointer to the end so new writes are placed after all existing content.with open(...) as f: block guarantee?with statement is a context manager. It calls __exit__ on the file object when the block ends, which closes the file even if an exception is raised.lines = f.readlines(). What type is lines?readlines() returns a list. Each element is a string for one line, including the newline character at the end. Use .strip() to remove it.Beyond the basics
readlines() could use a large amount of RAM. Better to iterate over the file object line by line (for line in f) so only one line is in memory at a time.Speed: Opening and closing the file once is fine, but if the program re-opens the file repeatedly inside the loop, the OS overhead adds up. The loop should be inside a single
with block.
Practice and Consolidation
scores.txt in append mode and write the string "95\n" to it. [3 marks]readline() and readlines(). [2 marks]