Objectives

Students will be able to:

  • show understanding of while files are needed
  • use pseudocode for file handling:
  • OPENFILE <filename> FOR READ/WRITE/APPEND
  • READFILE <filename>, <string>
  • WRITEFILE <filename>, <string>
  • CLOSEFILE <filename>
  • EOF <filename>
  • write program code for filehandling of a textfile

FILES

great for storing data

A computer program uses a data structure, for example an array, to store data. The problem is, when the computer is turned off, all of the data is lost.

One way to fix this problem is to store the data in a text file. ↓ is an example of a simple text file.

The data can be stored in the file and then read into the computer program line by line, possibly into an array, for example, for processing.

The computer program can also write new data into the text file. When the textfile is closed, all of the information will be available the next time it is opened.

One very interesting thing to note is that a text file stores text ie STRINGS. It does not store numbers as INTEGERS or REALS ie it stores "216" not 216.

Step 1 - OPEN THE FILE

pseudocode

OPENFILE "myText.txt" FOR WRITE

Python

f = open("myText.txt", "w")

Step 2 - WRITE TO THE FILE

pseudocode

OPENFILE "myText.txt" FOR WRITE

INPUT msg

WRITEFILE myText.txt, msg

Python

f = open("myText.txt", "w")

msg = input("Please type a message: ")

f.write(msg)

Step 3 - CLOSE THE FILE

pseudocode

OPENFILE "myText.txt" FOR WRITE

INPUT msg

WRITEFILE myText.txt, msg

CLOSEFILE myText.txt

Python

f = open("myText.txt", "w")

msg = input("Please type a message: ")

f.write(msg)

f.close()

Note: Text files only store text! They do not understand numbers eg INTEGERS or REALS.

Look at this code: would it work?

f = open("ages.txt", "w")

age = int(input("How old are you? "))

ageInDays = age*365

f.write(ageInDays)

f.close()

Do some research. How can we write a number into a textfile in Python?

Fix the above problem and share your solution with your teacher and/or classmate(s).

Feelings

How do you feel right now?