File objects in Python are created through the open() built-in function and serve as the primary interface for file operations. These objects expose a comprehensive set of methods for reading, writing, and manipulating file data.
File Object Methods
| Method | Description |
|---|---|
open(path, mode) |
Returns a file object. Modes include 'r' (read), 'w' (write), 'a' (append), 'r+' (read-write) |
read([n]) |
Retrieves up to n bytes; omits argument to read entire file |
write(text) |
Outputs string content to the file |
close() |
Terminates the file connection |
flush() |
Forces buffered data to disk immediately |
readline() |
Returns a single line from the file |
readlines() |
Returns all lines as a list |
tell() |
Reports current byte position in file |
seek(pos, ref) |
Moves cursor: ref 0=start, 1=current, 2=end |
fileno() |
Returns underlying file descriptor integer |
Reading Files
Reading an entire file into memory:
with open('data.txt', 'r') as handler:
data = handler.read()
print(data)
Processing lines sequentially:
with open('data.txt', 'r') as handler:
for line in handler:
print(line.rstrip())
Writing Files
Creating or overwriting a file:
with open('result.txt', 'w') as handler:
handler.write('First line\n')
handler.write('Second line')
Appending without overwriting:
with open('result.txt', 'a') as handler:
handler.write('\nAppended content')
Combined Read-Write Operations
with open('sample.txt', 'r+') as handler:
original = handler.read()
print('Initial:', original)
handler.seek(0)
handler.write('PREFIX\n')
handler.seek(0, 2)
handler.write('\nSUFFIX')
with open('sample.txt', 'r') as handler:
print('Updated:', handler.read())
Resource Maangement
Explicit closure approach:
handle = open('example.txt', 'r')
data = handle.read()
handle.close()
Context manager approach (preferred):
with open('example.txt', 'r') as handle:
data = handle.read()
The with statement guarantees cleanup even when exceptions occur, making it the recommended pattern for file handling in Python.