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.
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:
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.
Regardless of the programming language, the fundamental steps for performing file I/O are typically the same:
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).
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.
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.
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.
Here's a conceptual example using Python, which provides a simplified way to handle files with the `with` statement, ensuring files are automatically closed.
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")
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