Sequential Files and File-Processing Concepts
Construct code to perform file-processing operations
In this lesson
- Explaining why programs store data in files, and what a sequential file is
- Opening a text file to read, write or append, and closing it
- Reading a file line by line and processing its records
- Handling errors such as a missing file
LearnWhy files?
LearnOpen, use, close
LearnThe three modes
| Mode | Python | Java | If the file exists | If it does not exist |
|---|---|---|---|---|
| Read | open("f.txt", "r") | new BufferedReader(new FileReader("f.txt")) or new Scanner(new File("f.txt")) | Reading starts at the first line | Error: FileNotFoundError / FileNotFoundException |
| Write | open("f.txt", "w") | new FileWriter("f.txt") | Its contents are deleted at once (overwritten) | A new, empty file is created |
| Append | open("f.txt", "a") | new FileWriter("f.txt", true) | New text is added after the existing contents | A new, empty file is created |
CodeWriting a file
Saved 3 tasks
write does not add a newline, so "\n" is added to the end of each task. In Java, file operations can throw an IOException, which must be caught (or declared). try (FileWriter out = …) { … }, called try-with-resources, closes the file automatically at the end of the block, like Python’s with. Running the program a second time replaces the file rather than adding to it.
CodeAppending to a file
Task added
In Python, with open(...) as out: closes the file automatically at the end of the indented block, even if an error happens inside it. In Java, the second argument true to FileWriter means append; here the file is closed with an explicit close() call.
CodeReading line by line
1. Buy milk 2. Revise B2.5 3. Call Gran 4. Feed the cat
Java’s readLine() returns the line without its newline, and null at the end of the file. Python’s readline() keeps the newline (removed here with strip()) and returns an empty string at the end of the file.
CodeOther ways to read
4 tasks to do
Java’s Scanner reads a file with hasNextLine() and nextLine(). In Python, a for loop over the file object gives one line at a time.
CodeReading the whole file
celebrate: 2
article.txt contains three lines: Crowds celebrate the new park., The town celebrated all night. and More parks are planned. Python’s f.read() returns the whole file as one string; in Java the lines are joined into one string. The text is then split into words and the words starting with “celebrate” are counted: counting words like this is a simple way to estimate the mood of an article.
LabFiles step by step
Open, write, read and close files and see the code for each action. Text that has been written waits in a buffer until it is flushed, which happens at the latest when the file is closed.
Reset files restores the folder; tasks already ticked stay ticked.
scores.txtclosed
1 Ana,12 2 Ben,9
notes.txtdoes not exist
- Not done: Create notes.txt with two lines in it, and close it
- Not done: Add a third line to the end of notes.txt without losing the first two
- Not done: After adding the third line, read notes.txt line by line until the end of the file is reached
- Not done: Cause an error: e.g. read a file that does not exist, or use a file after closing it
CheckQuick check
A program records every login in log.txt. Which way of opening the file keeps all the earlier entries?
CheckRead, write or append?
Which mode should each task open the file in?
- Show every line of a saved report on the screen
- Replace a settings file with the user’s new settings
- Add each new order to the end of orders.txt
- Check whether a username is already in users.txt
- Start a brand-new results file for a new competition, removing last year’s results
- Record a sensor reading every minute, keeping all earlier readings
CodeProcessing records
Average: 11.75
scores.txt contains four records: Ana,12, Ben,9, Cleo,15 and Dev,11. split(",") separates its fields; the score is text and must be converted to a number before it can be added. The algorithms of B2.4 (totals, counts, maximum, searching) work the same way on lines read from a file.
LearnWhen things go wrong
CodeHandling a missing file
No settings file: using the defaults
settings.txt does not exist, so the program uses default settings instead of crashing.
ExamWorked exam answer
Construct a function (method) that saves the names in an array, one per line, to names.txt, replacing anything already in the file.
ReviewMistakes examiners see
Opening a file in write mode when the task needs to keep the existing data.
Forgetting the newline, so that every record ends up on one long line.
Doing arithmetic on a value read from a file without converting it from text to a number.
In a Construct answer, show all three steps: open in the right mode, read or write, close.
Exam practiceExam-style questions
4 questions · 13 marks. Answer each one first, then mark it yourself against the markscheme. Your answers are saved in this browser only.
A weather station stores its temperature readings in the text file temps.txt, one reading per line, e.g. 14.5.
Before this code runs, temps.txt contains the single line 18.0. State (i) what the file contains after the code has run, and (ii) the one change that would make the file keep all three readings.
Construct a function (method) that takes the name of a file of readings as a parameter and returns the highest temperature in it.
The station now stores each reading with its time, as a record such as 14:00,19.5. Construct a function (method) that takes a time and a reading and adds the record to the end of temps.txt, but only if the reading is from −50 to 60. It returns true if the record was saved and false otherwise, including when the file cannot be opened.
The station’s computer loses power while the program is running. write() had already been called for 40 readings since the file was opened, but none of them are in the file. Explain why, and suggest a change that limits how many readings can be lost.
0 of 4 questions marked. Mark every question to see your total.
Exam-style questions written for Praxis IB in the format of the 2027 specimen papers. They are not IB past-paper questions.