Resources | Subject Notes | Computer Science
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.
There are two main types of files we'll be working with:
When opening a file, you specify a mode that determines how the file will be accessed. Common modes include:
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)
Once a file is opened for reading, you can use various methods to read its contents.
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()
To write to a file, you open it in write mode ('w' or 'a') and use the write() method.
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()
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
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()
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")
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 |