Mastering File Operations in Python: Reading, Writing, and Beyond
After opening a file, various methods become available to retrieve its content.
Reading Entire Files
Use the read() method to load all data from the file at once.
with open('data.txt', 'r') as source:
full_text = source.read()
print(full_text)
Line-by-Line Processing
The readline() method reads one line at a time, enabling loop-based processing until no more lines remain.
with open('data.txt', 'r') as source:
current_line = source.readline()
while current_line:
print(current_line.strip())
current_line = source.readline()
Loading All Lines into Memory
readlines() returns a list containing each line of the file, useful for random access or batch operations.
with open('data.txt', 'r') as source:
all_lines = source.readlines()
for item in all_lines:
print(item.strip())
Writting Data to Files Different modes control how data is written.
Single Line Output
Use write() to insert text into the file. Note that this overwrites existing content if using 'w' mode.
with open('output.txt', 'w') as target:
target.write('Welcome to Python file handling!\n')
Multiple Lines with writelines() This method accepts an iterable of strings and writes them sequentially.
entries = ['First entry\n', 'Second entry\n', 'Final line\n']
with open('output.txt', 'w') as target:
target.writelines(entries)
Iterating Over Files Directly
File objects support iteration, allowing direct use in for loops for efficient line-by-line reading.
with open('data.txt', 'r') as input_file:
for line in input_file:
print(line.strip())
Using Context Managers
The with statement ensures proper cleanup even if an error occurs during file operations.
with open('data.txt', 'r') as handle:
content = handle.read()
print(content) # File closed automatically after block exit
Error Handling During I/O
Wrap file operations in try-except blocks to manage common issues like missing files or permission errors.
try:
with open('missing_file.txt', 'r') as doc:
data = doc.read()
print(data)
except FileNotFoundError:
print('Requested file not found.')
except PermissionError:
print('Access denied due to insufficient permissions.')
except Exception as err:
print(f'Unexpected issue: {err}')
Manual File Closure
Although discouraged when using with, close() can be called explicitly when managing file handles manually.
file_handle = open('temp.txt', 'r')
content = file_handle.read()
print(content)
file_handle.close() # Must call explicitly
Working with Binary Files
For non-text files such as images or binaries, use binary mode ('rb' or 'wb').
with open('image.jpg', 'rb') as image_data:
raw_bytes = image_data.read()
# Process bytes here
Controlling File Position
Use seek() to reposition the internal file pointer within the stream.
with open('sample.txt', 'r') as stream:
first_chunk = stream.read(10)
print(first_chunk)
stream.seek(0) # Return to start
second_read = stream.read(5)
print(second_read)
Summary Understanding file I/O in Python involves mastering reading strategies, writing patterns, error resilience, and low-level control via seek and context management. These tools enable robust, efficient, and safe interaction with both text and binary data sources.