B2.5.1Sequential Files and File-Processing Concepts
0/8
B2.5 File processingB2.5.1

Sequential Files and File-Processing Concepts

Construct code to perform file-processing operations

SL + HL≈ 70 minCommand term: ConstructFree lesson

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?

    0 of 4

    LearnOpen, use, close

      0 of 3

      LearnThe three modes

      ModePythonJavaIf the file existsIf it does not exist
      Readopen("f.txt", "r")new BufferedReader(new FileReader("f.txt")) or new Scanner(new File("f.txt"))Reading starts at the first lineError: FileNotFoundError / FileNotFoundException
      Writeopen("f.txt", "w")new FileWriter("f.txt")Its contents are deleted at once (overwritten)A new, empty file is created
      Appendopen("f.txt", "a")new FileWriter("f.txt", true)New text is added after the existing contentsA new, empty file is created

      CodeWriting a file

      tasks = ["Buy milk", "Revise B2.5", "Call Gran"]
      out = open("todo.txt", "w")
      for t in tasks:
      out.write(t + "\n")
      out.close()
      print("Saved", len(tasks), "tasks")
      Output
      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

      with open("todo.txt", "a") as out:
      out.write("Feed the cat\n")
      print("Task added")
      Output
      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

      with open("todo.txt", "r") as f:
      number = 1
      line = f.readline()
      while line != "":
      print(str(number) + ". " + line.strip())
      number = number + 1
      line = f.readline()
      Output
      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

      count = 0
      with open("todo.txt", "r") as f:
      for line in f:
      count = count + 1
      print(count, "tasks to do")
      Output
      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

      with open("article.txt", "r") as f:
      text = f.read()
      count = 0
      for word in text.split():
      if word.lower().startswith("celebrate"):
      count = count + 1
      print("celebrate:", count)
      Output
      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?

        1. Show every line of a saved report on the screen
        2. Replace a settings file with the user’s new settings
        3. Add each new order to the end of orders.txt
        4. Check whether a username is already in users.txt
        5. Start a brand-new results file for a new competition, removing last year’s results
        6. Record a sensor reading every minute, keeping all earlier readings

        CodeProcessing records

        total = 0
        count = 0
        with open("scores.txt", "r") as f:
        for line in f:
        parts = line.strip().split(",")
        total = total + int(parts[1])
        count = count + 1
        print("Average:", total / count)
        Output
        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

          0 of 3

          CodeHandling a missing file

          try:
          with open("settings.txt", "r") as f:
          print(f.readline().strip())
          except FileNotFoundError:
          print("No settings file: using the defaults")
          Output
          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.

          [4]
          def saveNames(names):
          with open("names.txt", "w") as out:
          for n in names:
          out.write(n + "\n")
          saveNames(["Ana", "Ben"])
            Try writing your own answer first.

            ReviewMistakes examiners see

            Misconception

            Opening a file in write mode when the task needs to keep the existing data.

            Misconception

            Forgetting the newline, so that every record ends up on one long line.

            Misconception

            Doing arithmetic on a value read from a file without converting it from text to a number.

            Exam tip

            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.

            Scenario

            A weather station stores its temperature readings in the text file temps.txt, one reading per line, e.g. 14.5.

            (a)State · AO1[2]

            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.

            first = open("temps.txt", "a")
            first.write("20.0\n")
            first.close()
            second = open("temps.txt", "w")
            second.write("21.5\n")
            second.close()
            (b)Construct · AO3[5]

            Construct a function (method) that takes the name of a file of readings as a parameter and returns the highest temperature in it.

            (c)Construct · AO3[4]

            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.

            (d)Explain · AO3[2]

            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 / 13

            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.