File Handling

Computer Science: KS3, topic 2.3.9

File Handling

We must be careful with the way that we access files so that we do not accidentally corrupt them.

Open the file

Open the file

  • First, we open the file for use, so that the program can read from or write to it.
  • We can do this using:
  • open("filename.txt", "r")
  • open("filename.txt", "w")
  • Opening with "r" will allow you to read from the file.
  • Opening with "w" will allow you to write to the file.
Assign the file to a variable

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 = open("filename.txt", "r")
  • myFile = open("filename.txt", "w")
Read / write

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.write() will write a line to the file.
Close 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?

Practise this topic for free