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