Loading notes...
Loading notes...
BCA • Chapter 7
Chapter 7 explores file I/O operations in Python, covering the different file modes, robust handling using the 'with' statement, reading/writing techniques, and cursor manipulation.
Programs naturally lose their data when they terminate because variables are stored in Random Access Memory (RAM), which is volatile. To persist data permanently, it must be saved to a non-volatile storage medium, typically a hard drive, in the form of a file. File Handling in Python allows your scripts to create, read, update, and delete files. This is essential for logging, saving game states, reading configuration files, and processing large datasets.
7.1 Opening and Closing Files
Python uses the built-in `open()` function to interact with files. It requires two primary arguments: the file path and the mode. It returns a file object. It is critically important to close the file using `.close()` when you are done to free up system resources and ensure all data is written to the disk.
# Syntax: file_object = open('filename.txt', 'mode')
try:
# Opening a file for writing
file = open('data.txt', 'w')
file.write("Hello, File!")
finally:
# Always close the file, even if an error occurs above
file.close()7.2 File Modes
The mode dictates what you are allowed to do with the file and how the file is prepared when opened.
7.3 The 'with' Statement (Context Managers)
Manually closing files using `.close()` is error-prone. If your program crashes before it reaches the close statement, the file remains open. Python provides the `with` statement, which automatically closes the file the moment the block of code exits, even if an exception is raised. This is the universally recommended way to handle files.
# Writing using 'with'. The file is automatically closed afterwards.
with open('log.txt', 'w') as file:
file.write("System started.\n")
file.write("Loading modules...\n")
# Appending to the same file
with open('log.txt', 'a') as file:
file.write("System successfully booted.\n")7.4 Reading Files
Python offers multiple ways to read data from a file, depending on how large the file is and how you want to process it.
with open('log.txt', 'r') as file:
# Reading the whole file
content = file.read()
print("--- Full Content ---")
print(content)
with open('log.txt', 'r') as file:
print("--- Reading Line by Line ---")
# Iterating over the file object directly is highly memory efficient
for line in file:
# using end='' because the line already contains a \n character
print(line, end='')7.5 File Cursor Manipulation: seek() and tell()
When you read or write to a file, an internal 'cursor' (or file pointer) moves forward. `tell()` returns the current byte position of the cursor, and `seek(offset)` moves the cursor to a specific byte.
with open('log.txt', 'r') as file:
print("Cursor at:", file.tell()) # Output: 0
first_line = file.readline()
print("Cursor now at:", file.tell())
# Move cursor back to the absolute beginning
file.seek(0)
# Now reading again will start from the top
data = file.read(5) # Read exactly 5 bytes/characters
print(data)