Open, read, write and close files

Resources | Subject Notes | Computer Science

File Handling

This section covers the fundamental concepts and techniques for working with files in a computer science context. We will explore how to open, read from, write to, and close files, which are essential for data persistence and program functionality.

What are Files?

A file is a named collection of data stored on a computer's storage device (e.g., hard drive, SSD). Files can contain text, images, audio, video, or any other type of data. They are organized into a hierarchical structure called a file system.

File Modes

When opening a file, we specify a mode that determines how the file will be accessed. Common file 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 appending. 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. If the file already exists, the operation fails.
  • 'r+' (Read and Write): Opens the file for both reading and writing.
  • 'w+' (Read and Write): Opens the file for both reading and writing. If the file exists, its contents are overwritten. If the file does not exist, a new file is created.
  • 'a+' (Read and Append): Opens the file for both reading and appending. New data is added to the end of the file. If the file does not exist, a new file is created.

File Operations

Opening a File

The open() function is used to open a file. It takes the filename and the mode as arguments. It returns a file pointer, which is used to interact with the file.

Example (Python):

file = open(\"my_file.txt\", \"r\")

Reading from a File

Several methods can be used to read data from a file:

  • read(): Reads the entire contents of the file 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.
  • Iterating over the file object: The file object can be directly iterated over to read lines one by one. This is often the most memory-efficient method for large files.

Example (Python):

file = open(\"my_file.txt\", \"r\")content = file.read()print(content)file.seek(0)  # Reset the file pointer to the beginningfor line in file:    print(line.strip()) # Remove leading/trailing whitespacefile.close()

Writing to a File

The write() method is used to write data to a file. It takes a string as an argument and writes it to the file.

Example (Python):

file = open(\"my_file.txt\", \"w\")file.write(\"This is some text.\")file.write(\"Another line of text.\")file.close()

The writelines() method can be used to write a list of strings to a file.

Closing a File

It is crucial to close a file after you have finished with it. This releases the resources associated with the file and ensures that any buffered data is written to disk. The close() method is used to close a file.

Example (Python):

file = open(\"my_file.txt\", \"r\")# ... perform operations on the file ...file.close()

Using the with statement ensures that the file is automatically closed, even if errors occur.

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

Example Program (Python)

This program reads data from a file, counts the number of lines, and then writes the line count to another file.

def process_file(input_filename, output_filename):    try:        with open(input_filename, 'r') as infile:            lines = infile.readlines()            line_count = len(lines)        with open(output_filename, 'w') as outfile:            outfile.write(f\"The file '{input_filename}' contains {line_count} lines.\")    except FileNotFoundError:        print(f\"Error: File '{input_filename}' not found.\")    except Exception as e:        print(f\"An error occurred: {e}\")# Example usage:process_file(\"input.txt\", \"output.txt\")

Table Summary of File Operations

Operation Mode Description Example (Python)
Open 'r', 'w', 'a', 'x', 'r+', 'w+', 'a+' Creates a file or opens an existing one for specified access. file = open(\"filename.txt\", \"r\")
Read 'r', 'r+', 'a+' Retrieves data from the file. content = file.read(), line = file.readline(), lines = file.readlines(), for line in file: ...
Write 'w', 'a', 'w+', 'a+' Writes data to the file. file.write(\"data\"), file.writelines(list_of_strings)
Append 'a', 'a+', 'w+' Adds data to the end of the file. file.write(\"data\"), file.writelines(list_of_strings)
Close N/A Releases the file resources. file.close(), with open(...) as file: ...
Suggested diagram: A diagram illustrating the flow of data between a program and a file, showing the open, read, write, and close operations.