Basic file-handling operations
Programs process and use dataUnits of information. In computing there can be different data types, including integers, characters and Boolean. Data is often acted on by instructions.. When the program finishes, or is closed, any data it held is lost. To prevent loss, data can be stored in a fileAnything you save. It could be a document, a piece of music, a collection of data or something else. 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 identifierA name given to a part of a program, such as a variable, constant, function, procedure or module., eg in PythonA high-level programming language.:
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 variableA memory location within a computer program where values are stored., or more commonly an arrayA set of data values of the same type, stored in a sequence in a computer program. Also known as a list. , 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.