±«Óătv

Basic file-handling operations

Programs process and use . When the program finishes, or is closed, any data it held is lost. To prevent loss, data can be stored in a so that it can be accessed again at a later date.

Files generally have two modes of operation:

  • read from (r) - the file is opened so that data can be read from it
  • write to (w) - the file is opened so that data can be written to it

Opening and closing files

A file must be opened before data can be read from or written to it. To open a file, it must be referred to by its , eg in :

file = open(‘scores.txt’,’r’)

This would open the file scores.txt and allow its contents to be read.

file = open(‘scores.txt’,’w’)

This would open the file scores.txt and allow it to have data written to it.

When a file is no longer needed, it must be closed, eg

file.close()

Reading from a file

Once a file has been opened, the records are read from it one line at a time. The data held in this record can be read into a , or more commonly an , eg

file = openRead("scores.txt")
                    score = myFile.readLine()
                    file.close()

Writing to a file

Data is written to a file using the write statement, eg

file = open('scores.txt','w')
                    file.write('Hello')
                    file.close()

The code above would open a file for writing called ‘scores.txt’, write the word ‘Hello’ and then close the file.