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

Programs use data, known as ‘values’. 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 ofComputer 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(‘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.

CSV file

Instead of using a text or txt file, a 'comma-separated values' (or CSV) file can be used. It allows to create a table of data, using commas. A CSV file contains the values in a table as a series of text lines organised so that each column value is separated by a comma and each record is on a separate line.

Examples

Doe, Jane, 07/02/17

Smith, John, 09/11/72

The reading and writing are the same as the txt file.