Opening Files with Different Modes
Python's built-in open() function provides various modes to handle files. Below are common examples:
- Append mode (creates file if missing):
file_handle = open('data.txt', 'a')
- Binary mode (for images, etc.):
file_handle = open('photo.jpg', 'rb')
Reading File Content
Once a file is opened, you can read its contants using several methods.
2.1 Read Entire Content
Use .read() to load the whole file into a string.
with open('data.txt', 'r') as f:
entire = f.read()
print(entire)
2.2 Line-by-Line Reading
Use .readline() to fetch one line at a time.
with open('data.txt', 'r') as f:
current = f.readline()
while current:
print(current, end='')
current = f.readline()
2.3 Read All Lines into List
.readlines() returns a list of all lines.
with open('data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line, end='')
Writing to Files
Writing behaviour depends on the mode used when opening the file.
3.1 Writing a Single Line
.write() writes a string to the file.
with open('data.txt', 'w') as f:
f.write('First line\n')
3.2 Writing Multiple Lines
.writelines() accepts an iterable of strings.
records = ['Alpha\n', 'Beta\n', 'Gamma\n']
with open('data.txt', 'w') as f:
f.writelines(records)
Iterating Over a File
File object are iterable, so you can use a for loop to read lines.
with open('data.txt', 'r') as f:
for line in f:
print(line, end='')
Context Manager (with Statement)
The with statement ensures proper resource cleanup. The file is automatically closed when the block exits.
with open('data.txt', 'r') as f:
content = f.read()
print(content) # File closed after block
Exception Hnadling for Robustness
File operations can raise errors such as FileNotFoundError or PermissionError. Use try-except to handle them gracefully.
try:
with open('missing.txt', 'r') as f:
data = f.read()
print(data)
except FileNotFoundError:
print("File does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Manual File Closing
Although with is preferred, you can manually close a file using .close().
f = open('data.txt', 'r')
content = f.read()
print(content)
f.close()
Binary File Operations
For non-text files (e.g., images, audio), open in binary mode by adding 'b' to the mode string.
with open('photo.jpg', 'rb') as f:
raw_data = f.read()
# Process binary data
File Pointer Positioning
The .seek() method moves the file pointer to a specific byte position.
with open('data.txt', 'r') as f:
first_chars = f.read(10) # Read first 10 characters
print(first_chars)
f.seek(0) # Jump back to start
again = f.read(5)
print(again)