File Handling
Computer Science: Edexcel IGCSE, topic 2.4.4
File Handling
We must be careful with the way we access files so that we do not accidentally corrupt them.

Open the file
- First, we open the file for use, so that the operating system knows that we are using it.
- We can do this using:
- openRead("filename.txt")
- openWrite("filename.txt")

Assign the file to a variable
- The file must be assigned to a variable so that we can keep referring to it.
- This can be done as follows:
- myFile = openRead("filename.txt")
- myFile = openWrite("filename.txt")

Read / write
- We can now read or write to the file using the following commands:
- myFile.readLine() will return the next line of a file as a string.
- myFile.writeLine(
) will write a line to the file. - myFile.endOfFile() will return True if we reach the end of the file.

Close the file
- Finally, we must close the file so that it is free for another program to access.
- We can do this using:
- myFile.close()
Test yourself on File Handling
File Handling
Which of these are valid file handling methods?
If we don't use the correct methods to access files, what might happen?
Why must we close a file?