Open, close and use a file for reading and writing

Resources | Subject Notes | Computer Science

IGCSE Computer Science - File Handling

IGCSE Computer Science 0478

Topic: Programming

Objective: Open, Close and Use a File for Reading and Writing

This section covers the fundamental concepts of working with files in a programming context. We will explore how to open files for reading and writing, perform basic operations on file contents, and ensure proper file handling to avoid errors.

File Types

There are two main types of files we'll be working with:

  • Text Files: Contain human-readable text. Examples include .txt, .csv, .log.
  • Binary Files: Contain data in a non-text format. Examples include .jpg, .exe, .doc. We will focus primarily on text files in this section.

File Modes

When opening a file, you specify a mode that determines how the file will be accessed. Common modes include:

  • 'r' (Read): Opens the file for reading. The file must exist.
  • 'w' (Write): Opens the file for writing. If the file exists, its contents are overwritten. If the file does not exist, a new file is created.
  • 'a' (Append): Opens the file for writing. New data is added to the end of the file. If the file does not exist, a new file is created.
  • 'x' (Exclusive Creation): Creates a new file. Fails if the file already exists.
  • 'r+' (Read and Write): Opens the file for both reading and writing.
  • 'w+' (Read and Write): Opens the file for both reading and writing. Existing contents are truncated (deleted).
  • 'a+' (Read and Append): Opens the file for both reading and appending.

File Operations

Opening a File

The first step is to open a file using a specific mode. This creates a connection between your program and the file on the storage device.

Example (Python):


file = open("my_file.txt", "r")  # Open for reading
file = open("new_file.txt", "w") # Open for writing (overwrites if exists)

Reading from a File

Once a file is opened for reading, you can use various methods to read its contents.

  • read(): Reads the entire file content into a single string.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines from the file and returns them as a list of strings.

Example (Python):


file = open("my_file.txt", "r")
content = file.read()
print(content)

file = open("my_file.txt", "r")
line1 = file.readline()
print(line1)

file = open("my_file.txt", "r")
lines = file.readlines()
for line in lines:
    print(line.strip()) # Remove leading/trailing whitespace
file.close()

Writing to a File

To write to a file, you open it in write mode ('w' or 'a') and use the write() method.

  • write(string): Writes the given string to the file.
  • writelines(list of strings): Writes a list of strings to the file.

Example (Python):


file = open("new_file.txt", "w")
file.write("This is the first line.\n")
file.write("This is the second line.\n")
file.writelines(["Line 3\n", "Line 4\n"])
file.close()

Closing a File

It's crucial to close a file after you're finished with it. This releases the resources held by the file and ensures that any buffered data is written to the disk. Failure to close files can lead to data loss or corruption.

Example (Python):


file.close()

Using the `with` statement is a recommended way to ensure files are closed automatically, even if errors occur.


with open("my_file.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed here

Error Handling

It's important to handle potential errors when working with files, such as the file not existing or insufficient permissions. `try...except` blocks are used for this purpose.

Example (Python):


try:
    file = open("nonexistent_file.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("Error: The file does not exist.")
except PermissionError:
    print("Error: You do not have permission to access the file.")
finally:
    if 'file' in locals() and not file.closed:
        file.close()

Example Program (Python)

This program reads lines from a file and writes them to a new file.


def copy_file(input_filename, output_filename):
    try:
        with open(input_filename, 'r') as infile, open(output_filename, 'w') as outfile:
            for line in infile:
                outfile.write(line)
        print(f"File '{input_filename}' copied to '{output_filename}' successfully.")
    except FileNotFoundError:
        print(f"Error: File '{input_filename}' not found.")
    except PermissionError:
        print(f"Error: Permission denied to access file '{input_filename}' or '{output_filename}'.")

# Example usage:
copy_file("input.txt", "output.txt")

Table Summary of File Modes

Mode Description Behavior if file exists Behavior if file does not exist
'r' Read File must exist Error
'w' Write File contents are overwritten New file is created
'a' Append New data is added to the end New file is created
'x' Exclusive Creation Error New file is created
'r+' Read and Write File must exist Error
'w+' Read and Write File contents are overwritten New file is created
'a+' Read and Append New data is added to the end New file is created
Suggested diagram: A diagram illustrating the flow of data between a program and a file, highlighting the open, read, write, and close operations.