CSEN102 Introduction to Computer Science: Lecture 10: File I/O (Input/Output)

This lecture for CSEN102: Introduction to Computer Science, given by Milad Ghantous, PhD, covers the essential topic of File Input/Output (I/O), which allows programs to interact with files on a computer's storage system.


10.1 Why File I/O?

So far, our programs have mostly dealt with data that is input directly by the user (e.g., from the keyboard) or is hardcoded into the program, and output displayed to the screen. However, for many real-world applications, it's necessary to store data permanently and process large amounts of information. File I/O provides the capability to:


10.2 Types of Files

Files are generally categorized into two main types based on how their data is stored and interpreted:

This lecture will primarily focus on text file I/O.


10.3 Basic File Operations

Regardless of the programming language, the fundamental steps for performing file I/O are typically the same:

1. Opening a File:

Before you can read from or write to a file, you must open it. When opening, you specify the file's name (and path if it's not in the current directory) and the mode in which you want to open it (e.g., read, write, append).

2. Reading from a File:

Once opened in read mode, data can be read from the file. You can read the entire file, read it line by line, or read a specified number of characters.

3. Writing to a File:

Once opened in write or append mode, data can be written to the file. This data typically comes from variables or expressions within your program.

4. Closing a File:

It is crucial to close a file after you have finished reading from or writing to it. Closing a file ensures that all buffered data is written to the disk and that the file resources are released, preventing data corruption or resource leaks.


10.4 Example (Conceptual Python File I/O)

Here's a conceptual example using Python, which provides a simplified way to handle files with the `with` statement, ensuring files are automatically closed.

Writing to a file:

with open("my_data.txt", "w") as file:
    file.write("Hello, world!\n")
    file.write("This is a new line.\n")
print("Data written to my_data.txt")
    

Reading from a file:

with open("my_data.txt", "r") as file:
    content = file.read() # Reads entire file content
    print(content)

# Alternatively, read line by line:
with open("my_data.txt", "r") as file:
    for line in file:
        print(line.strip()) # .strip() removes newline characters
    

File I/O is a fundamental skill for any programmer, enabling programs to interact with persistent data and perform more complex and practical tasks.

Thank you