成人论坛

Data types, structures and operators - EdexcelBasic file-handling operations

Programs use data, known as 鈥榲alues鈥. Variables hold values. Each variable in a program must have a data type. Sometimes a programmer needs to store a lot of related data. To do this they use structures such as arrays.

Part of Computer ScienceApplication of computational thinking

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(鈥榮cores.txt鈥,鈥檙鈥)

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

file = open(鈥榮cores.txt鈥,鈥檞鈥)

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 鈥榮cores.txt鈥, write the word 鈥楬ello鈥 and then close the file.