File modes in Python define how a file is opened — for reading, writing, appending, etc. Choosing the correct mode is essential for proper file handling and data safety.
'r'
- Read (default). Fails if file does not exist.'w'
- Write. Creates new or overwrites existing file.'a'
- Append. Adds to end of file. Creates if not found.'r+'
- Read & write. File must exist.'w+'
- Write & read. Overwrites file.'a+'
- Append & read. File pointer at end.'b'
- Binary mode (add to other modes, e.g., 'rb'
).'x'
- Exclusive creation. Fails if file exists.with open('sample.txt', 'r') as file:
print(file.read())
with open('output.txt', 'w') as file:
file.write('Overwriting content\\n')
with open('log.txt', 'a') as file:
file.write('Appended line\\n')
with open('sample.txt', 'r+') as file:
content = file.read()
file.seek(0)
file.write('Updated content\\n')
with open('data.txt', 'w+') as file:
file.write('New Data\\n')
file.seek(0)
print(file.read())
with open('data.txt', 'a+') as file:
file.write('More data\\n')
file.seek(0)
print(file.read())
with open('image.jpg', 'rb') as file:
data = file.read()
print(f'{len(data)} bytes read')
binary_data = b'\\x41\\x42\\x43'
with open('binary.bin', 'wb') as file:
file.write(binary_data)
try:
with open('unique.txt', 'x') as file:
file.write('This file is created exclusively')
except FileExistsError:
print("File already exists!")
try:
with open('data.txt', 'z') as file:
pass
except ValueError as e:
print("Invalid mode:", e)