Test your knowledge with free interactive questions on Seneca — used by over 10 million students.

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 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.
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 refering 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()
Jump to other topics
1

Computational Thinking & Algorithms

2

Programming

3

Hardware & Software

4

Data

5

The Internet

6

Online Safety & Security

Practice questions on File Handling

Can you answer these? Test yourself with free interactive practice on Seneca — used by over 10 million students.

  1. 1
    File HandlingPut in order
  2. 2
  3. 3
  4. 4
Answer all questions on File Handling

Unlock your full potential with Seneca Premium

  • Unlimited access to 10,000+ open-ended exam questions

  • Mini-mock exams based on your study history

  • Unlock 800+ premium courses & e-books

Get started with Seneca Premium