Skip to content
Book 4: Practical Programming

Book 4 · Chapter P4.3

Text files

§10.3AS skills Paper 4 builds onRegular · ≈ 4.1 m · ↘B4·3

This 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.

Open in the ebook

For the whole chapter

§10.3 Files

Short code 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()
Three names written, then read back and numbered. Predict the output before you read it.

Output

1 AishaBilalChen
Run and checked before printing
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()
The same program with a line break after each name. Python's write needs "\n"; VB.NET's WriteLine adds it; Java's write needs "\n" too.

Output

1 Aisha
2 Bilal
3 Chen
Run and checked before printing

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")
Writing a file. Each record becomes one line of text: the mark is converted to a string and joined to the name with a comma.

Output

Written: Aisha,72
Written: Bilal,58
Written: Chen,91
Marks.txt closed
Run and checked before printing
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();
    }
}
Java: write(72) writes the character whose code is 72, the letter H. write("72") writes the digits.

Output

H
72
Run and checked before printing
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()
Python: 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
Run and checked before printing

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))
WRITE starts the file again; APPEND keeps what is there and adds after it. Two names are written, then a third is appended.

Output

Aisha
Bilal
Chen
Lines: 3
Run and checked before printing
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 Module
VB.NET: New 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
Run and checked before printing

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))
Reading a file line by line until the end. The test for the end comes before each line is used, so an empty file gives no passes at all.

Output

1: Aisha,Red,72
2: Bilal,Blue,58
3: Chen,Red,91
4: Dara,Green,45
5: Ehsan,Blue,66
Lines read: 5
Run and checked before printing
# 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))
Python's shorter idiom: 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
Run and checked before printing
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()
Python's 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
Run and checked before printing
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"))
The first Mark Ladder's model answer, run on Scores.txt (5 lines) and on an empty file.

Output

5
0
Run and checked before printing
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 Module
The faded twin's model answer (LongestLine), run on Scores.txt: its longest lines have 13 characters.

Output

13
Run and checked before printing

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()
A file that is written but not closed can be empty when it is read: the line is still waiting in memory. Closing first fixes it.

Output

Not closed: []
Closed: [Revise files]
Run and checked before printing
# 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)
Python's 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
Run and checked before printing

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)
Splitting a line at its commas gives an array of strings. The score is converted to an integer before any arithmetic.

Output

Chen of Red scored 91
With the bonus: 96
Run and checked before printing
Fields = "Aisha,72,58".split(",")
print(Fields[1] + Fields[2])
print(int(Fields[1]) + int(Fields[2]))
Fields from a split are strings, so + joins them. Convert first, then add.

Output

7258
130
Run and checked before printing

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))
One field per line: each pass reads two lines, a name and then its score, so the end-of-file test is made once per record.

Output

Aisha scored 72
Bilal scored 58
Chen scored 91
Records: 3
Run and checked before printing

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)
Loading a file into an array of records. Each line is split into three fields, the score is converted, and a counter says how many elements are in use; the loop also stops when the array is full.

Output

Loaded 5 players
Aisha Red 72
Bilal Blue 58
Chen Red 91
Dara Green 45
Ehsan Blue 66
Run and checked before printing
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])
The second Mark Ladder's model answer, run on a four-line Marks.txt.

Output

4
Chen 91
Run and checked before printing
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;
}
The faded twin's model answer (LoadBooks), run on a three-line Books.txt.

Output

3
Kim 1901
Run and checked before printing

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))
Processing the loaded records: a total for one house, and the index of the best score. Both loops stop at PlayerCount, not at the size of the array.

Output

Red: 163
Blue: 124
Green: 45
Best: Chen with 91
Run and checked before printing
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)
Counting the lines that match a condition, straight from the file: no array is needed when each line is used once. A house with no players gives 0.

Output

Red: 2
Blue: 2
Green: 1
Yellow: 0
Run and checked before printing

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()
Writing records back out: each record is joined into one line, fields separated by commas, numbers converted to text. The last lines read Results.txt back to show what was written.

Output

Aisha,72,PASS
Bilal,58,RETAKE
Chen,91,PASS
Dara,45,RETAKE
Ehsan,66,PASS
Run and checked before printing
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()
The third Mark Ladder's model answer: three names and marks saved, then the file read back.

Output

Aisha,72
Bilal,58
Chen,91
Run and checked before printing
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 Module
The faded twin's model answer (SavePassList): only the marks of 60 or more are written.

Output

Aisha
Chen
Run and checked before printing

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()
Read one file, write another: the lines for one house are copied to a new file and counted. Both files are closed after the loop.

Output

Copied 2 lines to Red.txt
Aisha,Red,72
Chen,Red,91
Run and checked before printing

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")
A missing file handled: the statements that use the file go inside the try; the except / Catch / catch outputs a message instead of letting the program stop.

Output

Absent.txt: file not found
Scores.txt: 5 lines
Run and checked before printing
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")
An 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
Run and checked before printing

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()
The whole task in three languages: load 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
Run and checked before printing

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.

Ask Z about Text files
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook