2.2.13

File Handling

Test yourself

Files

Without files, we can only store data in the memory.

Illustrative background for FilesIllustrative background for Files ?? "content

Files

  • Files allow us to store data so that it persists even when our program is not running.
  • This allows programs to 'carry on where they left off' when they are executed.
Illustrative background for Text filesIllustrative background for Text files ?? "content

Text files

  • Text files consist of string data that can be read and processed by many applications.
Illustrative background for Binary filesIllustrative background for Binary files ?? "content

Binary files

  • Binary files consist of binary data that is read and processed by specific applications.

File Handling

We must be careful with the way 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:
    • openRead("filename.txt")
    • openWrite("filename.txt")
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 = openRead("filename.txt")
    • myFile = openWrite("filename.txt")
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.writeLine() will write a line to the file.
    • myFile.endOfFile() will return True if we reach the end of 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

1Computer Systems

1.1Systems Architecture

1.2Memory & Storage

1.3Computer Networks, Connections & Protocols

1.4Network Security

1.5Systems Software

1.6Ethical, Legal, Cultural & Environmental Concern

2Computational Thinking, Algorithms and Programming

2.1Algorithms

2.2Programming Fundamentals

2.3Producing Robust Programs

2.4Boolean Logic

2.5Programming Languages & IDEs

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