2.3.9

File Handling

Test yourself

File Handling

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

Illustrative background for Open the fileIllustrative background for Open the file ?? "content

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:
    • open("filename.txt", "r")
    • open("filename.txt", "w")
  • Opening with "r" will allow you read access to the file.
  • Opening with "w" will allow you write access to the file.
Illustrative background for Assign the file to a variableIllustrative background for Assign the file to a variable ?? "content

Assign the file to a variable

  • The file must be assigned to a variable so that we can keep refering to it.
  • This can be done as follows:
    • myFile = open("filename.txt", "r")
    • myFile = open("filename.txt", "w")
Illustrative background for Read / writeIllustrative background for Read / write ?? "content

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.
Illustrative background for Close the fileIllustrative background for Close the file ?? "content

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()

Jump to other topics

1Computational Thinking & Algorithms

2Programming

3Hardware & Software

4Data

5The Internet

6Online Safety & Security

Go student ad image

Unlock your full potential with GoStudent tutoring

  • Affordable 1:1 tutoring from the comfort of your home

  • Tutors are matched to your specific learning needs

  • 30+ school subjects covered

Book a free trial lesson