Book 4 · Chapter P4.3
Text files
B4·3This chapter is in the ebook.
Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.
For the whole chapter
- Topic pageData Types and Structures
B4·3·T - QuizData Types & Structures
B4·3·Q1 - LabData Structures Playground
B4·3·X1 - LabBubble sort & linear search
B4·3·X2 - LabRecord & file tasks
B4·3·X3
§10.3 Files
Short code B4·3·1
- FlashcardsFlashcards §10.3–10.4: Text files & implementing ADTs
B4·3·F1 - Past-paper questionsPast-paper questions §10.3 (files)
B4·3·1
Text files in your toolkit
Short code B4·3·10
File = open("Team.txt", "w")
File.write("Aisha")
File.write("Bilal")
File.write("Chen")
File.close()
File = open("Team.txt", "r")
Count = 0
Line = File.readline()
while Line != "":
Count = Count + 1
print(Count, Line)
Line = File.readline()
File.close()Output
1 AishaBilalChen
File = open("Team.txt", "w")
File.write("Aisha\n")
File.write("Bilal\n")
File.write("Chen\n")
File.close()
File = open("Team.txt", "r")
Count = 0
Line = File.readline()
while Line != "":
Count = Count + 1
print(Count, Line.strip())
Line = File.readline()
File.close()write needs "\n"; VB.NET's WriteLine adds it; Java's write needs "\n" too.Output
1 Aisha 2 Bilal 3 Chen
Part A: from OPENFILE to code
Short code B4·3·11
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Writing a file
Short code B4·3·12
Names = ["Aisha", "Bilal", "Chen"]
Marks = [72, 58, 91]
File = open("Marks.txt", "w")
for Index in range(3):
Line = Names[Index] + "," + str(Marks[Index])
File.write(Line + "\n")
print("Written: " + Line)
File.close()
print("Marks.txt closed")Output
Written: Aisha,72 Written: Bilal,58 Written: Chen,91 Marks.txt closed
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter Writer = new FileWriter("Codes.txt");
Writer.write(72);
Writer.write("\n");
Writer.write("72\n");
Writer.close();
BufferedReader Reader = new BufferedReader(new FileReader("Codes.txt"));
String Line = Reader.readLine();
while (Line != null) {
System.out.println(Line);
Line = Reader.readLine();
}
Reader.close();
}
}write(72) writes the character whose code is 72, the letter H. write("72") writes the digits.Output
H 72
File = open("Codes.txt", "w")
try:
File.write(72)
except TypeError as Problem:
print(Problem)
File.write(str(72) + "\n")
print("72 written")
File.close()write takes only a string. Given the number 72 it stops the program; str(72) fixes it.Output
write() argument must be str, not int 72 written
Appending
Short code B4·3·13
File = open("Team.txt", "w")
File.write("Aisha\n")
File.write("Bilal\n")
File.close()
File = open("Team.txt", "a")
File.write("Chen\n")
File.close()
Count = 0
File = open("Team.txt", "r")
Line = File.readline()
while Line != "":
print(Line.strip())
Count = Count + 1
Line = File.readline()
File.close()
print("Lines: " + str(Count))Output
Aisha Bilal Chen Lines: 3
Imports System.IO
Module Program
Sub Main()
Dim Writer As New StreamWriter("Team.txt")
Writer.WriteLine("Aisha")
Writer.WriteLine("Bilal")
Writer.Close()
Writer = New StreamWriter("Team.txt")
Writer.WriteLine("Chen")
Writer.Close()
Dim Count As Integer = 0
Dim Reader As New StreamReader("Team.txt")
Do While Not Reader.EndOfStream
Console.WriteLine(Reader.ReadLine())
Count = Count + 1
Loop
Reader.Close()
Console.WriteLine("Lines: " & Count)
End Sub
End ModuleNew IO.StreamWriter("Team.txt") with no second argument starts the file again, so only Chen is left. New IO.StreamWriter("Team.txt", True) would have kept Aisha and Bilal.Output
Chen Lines: 1
Reading line by line
Short code B4·3·14
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
Count = 0
File = open("Scores.txt", "r")
Line = File.readline()
while Line != "":
Line = Line.strip()
Count = Count + 1
print(str(Count) + ": " + Line)
Line = File.readline()
File.close()
print("Lines read: " + str(Count))Output
1: Aisha,Red,72 2: Bilal,Blue,58 3: Chen,Red,91 4: Dara,Green,45 5: Ehsan,Blue,66 Lines read: 5
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
Count = 0
File = open("Scores.txt", "r")
for Line in File:
Count = Count + 1
print(str(Count) + ": " + Line.strip())
File.close()
print("Lines read: " + str(Count))for Line in File reads one line per pass and stops at the end of the file by itself.Output
1: Aisha,Red,72 2: Bilal,Blue,58 3: Chen,Red,91 4: Dara,Green,45 5: Ehsan,Blue,66 Lines read: 5
File = open("Team.txt", "w")
File.write("Aisha\nBilal\n")
File.close()
File = open("Team.txt", "r")
Line = File.readline()
print(repr(Line))
print(Line == "Aisha")
print(Line.strip() == "Aisha")
File.close()readline keeps the line break at the end of the line, so the line is not equal to "Aisha" until it is stripped.Output
'Aisha\n' False True
def CountLines(FileName):
Count = 0
File = open(FileName, "r")
Line = File.readline()
while Line != "":
Count = Count + 1
Line = File.readline()
File.close()
return Count
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
Empty = open("Empty.txt", "w")
Empty.close()
print(CountLines("Scores.txt"))
print(CountLines("Empty.txt"))Scores.txt (5 lines) and on an empty file.Output
5 0
Imports System.IO
Module Program
Function LongestLine(FileName As String) As Integer
Dim Longest As Integer = 0
Dim Line As String
Dim Reader As New StreamReader(FileName)
Do While Not Reader.EndOfStream
Line = Reader.ReadLine()
If Len(Line) > Longest Then
Longest = Len(Line)
End If
Loop
Reader.Close()
Return Longest
End Function
Sub Main()
' test file: supplied on Paper 4
File.WriteAllText("Scores.txt",
"Aisha,Red,72" & vbLf &
"Bilal,Blue,58" & vbLf &
"Chen,Red,91" & vbLf &
"Dara,Green,45" & vbLf &
"Ehsan,Blue,66" & vbLf)
Console.WriteLine(LongestLine("Scores.txt"))
End Sub
End ModuleLongestLine), run on Scores.txt: its longest lines have 13 characters.Output
13
Closing the file
Short code B4·3·15
File = open("Notes.txt", "w")
File.write("Revise files\n")
Reader = open("Notes.txt", "r")
Text = Reader.readline().strip()
print("Not closed: [" + Text + "]")
Reader.close()
File.close()
Reader = open("Notes.txt", "r")
Text = Reader.readline().strip()
print("Closed: [" + Text + "]")
Reader.close()Output
Not closed: [] Closed: [Revise files]
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
Count = 0
with open("Scores.txt", "r") as File:
for Line in File:
Count = Count + 1
print("Lines read: " + str(Count))
print("Closed:", File.closed)with closes the file by itself when the indented block ends, even if the block stops with an error.Output
Lines read: 5 Closed: True
Part B: splitting a line into fields
Short code B4·3·16
Line = "Chen,Red,91"
Fields = Line.split(",")
PlayerName = Fields[0]
House = Fields[1]
Score = int(Fields[2])
print(PlayerName, "of", House, "scored", Score)
print("With the bonus:", Score + 5)Output
Chen of Red scored 91 With the bonus: 96
Fields = "Aisha,72,58".split(",")
print(Fields[1] + Fields[2])
print(int(Fields[1]) + int(Fields[2]))+ joins them. Convert first, then add.Output
7258 130
One field per line
Short code B4·3·17
# test file: supplied on Paper 4
TestFile = open("HighScores.txt", "w")
TestFile.write("Aisha\n72\n"
"Bilal\n58\n"
"Chen\n91\n")
TestFile.close()
Count = 0
File = open("HighScores.txt", "r")
PlayerName = File.readline()
while PlayerName != "":
Score = int(File.readline())
print(PlayerName.strip(), "scored", Score)
Count = Count + 1
PlayerName = File.readline()
File.close()
print("Records: " + str(Count))Output
Aisha scored 72 Bilal scored 58 Chen scored 91 Records: 3
Loading a file into an array of records
Short code B4·3·18
class Player:
# a record type: fields only
def __init__(self):
self.PlayerName = "" # STRING
self.House = "" # STRING
self.Score = 0 # INTEGER
MAXPLAYERS = 10 # constant
Players = [None] * MAXPLAYERS # ARRAY[0:9] OF Player
PlayerCount = 0 # global INTEGER
def LoadPlayers(FileName):
global PlayerCount
PlayerCount = 0
File = open(FileName, "r")
Line = File.readline()
while Line != "" and PlayerCount < MAXPLAYERS:
Fields = Line.strip().split(",")
NewPlayer = Player()
NewPlayer.PlayerName = Fields[0]
NewPlayer.House = Fields[1]
NewPlayer.Score = int(Fields[2])
Players[PlayerCount] = NewPlayer
PlayerCount = PlayerCount + 1
Line = File.readline()
File.close()
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
LoadPlayers("Scores.txt")
print("Loaded", PlayerCount, "players")
for Index in range(PlayerCount):
print(Players[Index].PlayerName, Players[Index].House, Players[Index].Score)Output
Loaded 5 players Aisha Red 72 Bilal Blue 58 Chen Red 91 Dara Green 45 Ehsan Blue 66
Names = [""] * 20 # ARRAY[0:19] OF STRING
Marks = [0] * 20 # ARRAY[0:19] OF INTEGER
MarkCount = 0 # global INTEGER
def LoadMarks():
global MarkCount
MarkCount = 0
File = open("Marks.txt", "r")
Line = File.readline()
while Line != "" and MarkCount < 20:
Fields = Line.strip().split(",")
Names[MarkCount] = Fields[0]
Marks[MarkCount] = int(Fields[1])
MarkCount = MarkCount + 1
Line = File.readline()
File.close()
# test file: supplied on Paper 4
TestFile = open("Marks.txt", "w")
TestFile.write("Aisha,72\nBilal,58\nChen,91\nDara,45\n")
TestFile.close()
LoadMarks()
print(MarkCount)
print(Names[2], Marks[2])Marks.txt.Output
4 Chen 91
import java.io.*;
import java.nio.file.*;
public class Main {
static Book[] Books = new Book[50];
static int BookCount = 0;
static void LoadBooks() throws IOException {
BookCount = 0;
BufferedReader Reader = new BufferedReader(new FileReader("Books.txt"));
String Line = Reader.readLine();
while (Line != null && BookCount < 50) {
String[] Fields = Line.split(",");
Books[BookCount] = new Book();
Books[BookCount].Title = Fields[0];
Books[BookCount].Year = Integer.parseInt(Fields[1]);
BookCount = BookCount + 1;
Line = Reader.readLine();
}
Reader.close();
}
public static void main(String[] args) throws IOException {
// test file: supplied on Paper 4
Files.writeString(Path.of("Books.txt"),
"Dune,1965\nEmma,1815\n" +
"Kim,1901\n");
LoadBooks();
System.out.println(BookCount);
System.out.println(Books[2].Title + " " + Books[2].Year);
}
}
class Book {
String Title = "";
int Year = 0;
}LoadBooks), run on a three-line Books.txt.Output
3 Kim 1901
Processing the records, counting matches
Short code B4·3·19
class Player:
# a record type: fields only
def __init__(self):
self.PlayerName = "" # STRING
self.House = "" # STRING
self.Score = 0 # INTEGER
MAXPLAYERS = 10 # constant
Players = [None] * MAXPLAYERS # ARRAY[0:9] OF Player
PlayerCount = 0 # global INTEGER
def LoadPlayers(FileName):
global PlayerCount
PlayerCount = 0
File = open(FileName, "r")
Line = File.readline()
while Line != "" and PlayerCount < MAXPLAYERS:
Fields = Line.strip().split(",")
NewPlayer = Player()
NewPlayer.PlayerName = Fields[0]
NewPlayer.House = Fields[1]
NewPlayer.Score = int(Fields[2])
Players[PlayerCount] = NewPlayer
PlayerCount = PlayerCount + 1
Line = File.readline()
File.close()
def HouseTotal(House):
Total = 0
for Index in range(PlayerCount):
if Players[Index].House == House:
Total = Total + Players[Index].Score
return Total
def BestPlayer():
Best = 0
for Index in range(1, PlayerCount):
Score = Players[Index].Score
if Score > Players[Best].Score:
Best = Index
return Best
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
LoadPlayers("Scores.txt")
for House in ["Red", "Blue", "Green"]:
print(House + ": " + str(HouseTotal(House)))
Top = BestPlayer()
print("Best: " + Players[Top].PlayerName + " with " + str(Players[Top].Score))PlayerCount, not at the size of the array.Output
Red: 163 Blue: 124 Green: 45 Best: Chen with 91
def CountHouse(FileName, House):
Count = 0
File = open(FileName, "r")
Line = File.readline()
while Line != "":
Fields = Line.strip().split(",")
if Fields[1] == House:
Count = Count + 1
Line = File.readline()
File.close()
return Count
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
for House in ["Red", "Blue", "Green", "Yellow"]:
Count = CountHouse("Scores.txt", House)
print(House + ":", Count)Output
Red: 2 Blue: 2 Green: 1 Yellow: 0
Writing records back out
Short code B4·3·20
class Player:
# a record type: fields only
def __init__(self):
self.PlayerName = "" # STRING
self.House = "" # STRING
self.Score = 0 # INTEGER
MAXPLAYERS = 10 # constant
Players = [None] * MAXPLAYERS # ARRAY[0:9] OF Player
PlayerCount = 0 # global INTEGER
def LoadPlayers(FileName):
global PlayerCount
PlayerCount = 0
File = open(FileName, "r")
Line = File.readline()
while Line != "" and PlayerCount < MAXPLAYERS:
Fields = Line.strip().split(",")
NewPlayer = Player()
NewPlayer.PlayerName = Fields[0]
NewPlayer.House = Fields[1]
NewPlayer.Score = int(Fields[2])
Players[PlayerCount] = NewPlayer
PlayerCount = PlayerCount + 1
Line = File.readline()
File.close()
def WriteResults(FileName):
File = open(FileName, "w")
for Index in range(PlayerCount):
Score = Players[Index].Score
if Score >= 60:
Result = "PASS"
else:
Result = "RETAKE"
Line = Players[Index].PlayerName + "," + str(Score)
File.write(Line + "," + Result + "\n")
File.close()
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
LoadPlayers("Scores.txt")
WriteResults("Results.txt")
File = open("Results.txt", "r")
for Line in File:
print(Line.strip())
File.close()Results.txt back to show what was written.Output
Aisha,72,PASS Bilal,58,RETAKE Chen,91,PASS Dara,45,RETAKE Ehsan,66,PASS
Names = ["Aisha", "Bilal", "Chen", "", ""]
Marks = [72, 58, 91, 0, 0]
MarkCount = 3
def SaveMarks(FileName):
File = open(FileName, "w")
for Index in range(MarkCount):
File.write(Names[Index] + "," + str(Marks[Index]) + "\n")
File.close()
SaveMarks("Saved.txt")
File = open("Saved.txt", "r")
for Line in File:
print(Line.strip())
File.close()Output
Aisha,72 Bilal,58 Chen,91
Imports System.IO
Module Program
Dim Names() As String = {"Aisha", "Bilal", "Chen", "", ""}
Dim Marks() As Integer = {72, 58, 91, 0, 0}
Dim MarkCount As Integer = 3
Sub SavePassList(FileName As String)
Dim Writer As New StreamWriter(FileName)
For Index As Integer = 0 To MarkCount - 1
If Marks(Index) >= 60 Then
Writer.WriteLine(Names(Index))
End If
Next
Writer.Close()
End Sub
Sub Main()
SavePassList("Pass.txt")
Dim Reader As New StreamReader("Pass.txt")
Do While Not Reader.EndOfStream
Console.WriteLine(Reader.ReadLine())
Loop
Reader.Close()
End Sub
End ModuleSavePassList): only the marks of 60 or more are written.Output
Aisha Chen
Read one file, write another
Short code B4·3·21
def CopyHouse(InFile, OutFile, House):
Copied = 0
Source = open(InFile, "r")
Target = open(OutFile, "w")
Line = Source.readline()
while Line != "":
Fields = Line.strip().split(",")
if Fields[1] == House:
Target.write(Line)
Copied = Copied + 1
Line = Source.readline()
Source.close()
Target.close()
return Copied
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
Count = CopyHouse("Scores.txt", "Red.txt", "Red")
print("Copied " + str(Count) + " lines to Red.txt")
File = open("Red.txt", "r")
for Line in File:
print(Line.strip())
File.close()Output
Copied 2 lines to Red.txt Aisha,Red,72 Chen,Red,91
Part C: when the file is not there
Short code B4·3·22
def ReportLines(FileName):
try:
File = open(FileName, "r")
Count = 0
Line = File.readline()
while Line != "":
Count = Count + 1
Line = File.readline()
File.close()
print(FileName + ":", Count, "lines")
except FileNotFoundError:
print(FileName + ": file not found")
# test file: supplied on Paper 4
TestFile = open("Scores.txt", "w")
TestFile.write("Aisha,Red,72\nBilal,Blue,58\n"
"Chen,Red,91\nDara,Green,45\n"
"Ehsan,Blue,66\n")
TestFile.close()
ReportLines("Absent.txt")
ReportLines("Scores.txt")try; the except / Catch / catch outputs a message instead of letting the program stop.Output
Absent.txt: file not found Scores.txt: 5 lines
PlayerCount = 0
def LoadPlayers(FileName):
global PlayerCount
try:
File = open(FileName, "r")
for Line in File:
PlayerCount = PlayerCount + 1
File.close()
except:
pass
LoadPlayers("Scorse.txt")
print("Loaded", PlayerCount, "players")except that does nothing hides the problem: the misspelt file name loads no players and the program carries on as if the file were empty.Output
Loaded 0 players
A whole Paper 4 file task
Short code B4·3·23
class Reading:
# a record type: fields only
def __init__(self):
self.Day = "" # STRING
self.Temp = 0 # INTEGER
MAXREADINGS = 31 # constant
Readings = [None] * MAXREADINGS # ARRAY[0:30] OF Reading
ReadingCount = 0 # global INTEGER
def LoadReadings(FileName):
global ReadingCount
ReadingCount = 0
try:
File = open(FileName, "r")
Line = File.readline()
while Line != "" and ReadingCount < MAXREADINGS:
Fields = Line.strip().split(",")
NewReading = Reading()
NewReading.Day = Fields[0]
NewReading.Temp = int(Fields[1])
Readings[ReadingCount] = NewReading
ReadingCount = ReadingCount + 1
Line = File.readline()
File.close()
except FileNotFoundError:
print("Cannot find " + FileName)
def MeanTemp():
Total = 0
for Index in range(ReadingCount):
Total = Total + Readings[Index].Temp
return Total // ReadingCount
def WriteWarmDays(FileName, Mean):
Written = 0
File = open(FileName, "w")
for Index in range(ReadingCount):
Temp = Readings[Index].Temp
if Temp > Mean:
Day = Readings[Index].Day
File.write(Day + "," + str(Temp) + "\n")
Written = Written + 1
File.close()
return Written
# test file: supplied on Paper 4
TestFile = open("Temps.txt", "w")
TestFile.write("Mon,18\nTue,23\nWed,21\nThu,25\n"
"Fri,19\nSat,26\nSun,22\n")
TestFile.close()
LoadReadings("Temps.txt")
if ReadingCount > 0:
Mean = MeanTemp()
Warm = WriteWarmDays("WarmDays.txt", Mean)
print("Readings: " + str(ReadingCount) + ", mean: " + str(Mean))
print("Days above the mean: " + str(Warm))
File = open("WarmDays.txt", "r")
for Line in File:
print(Line.strip())
File.close()Temps.txt into an array of records, work out the mean, write the days above it to WarmDays.txt and count them. The last lines read the results file back.Output
Readings: 7, mean: 22 Days above the mean: 3 Tue,23 Thu,25 Sat,26
Workbook 4: Text files
Short code W4·3 · Practical Programming Task Book
The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.
Starter files
Short code W4·3·K
Data files and skeleton code in Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.


