The open() function is a built-in function in Python used to open files. It opens a file and returns a file object for reading, writing, appending, and other file operations.
Function Syntax
open(file, mode='r', buffering=-1,
encoding=None, errors=None, newline=None,
closefd=True, opener=None)
Parameter Details
file
Required parameter, file path and name to open. Can use relative or absolute paths.
# Relative paths
open('data.txt')
open('../parent/data.txt')
# Absolute paths Windows
open(r'C:\Users\name\data.txt')
open('C:\\Users\\name\\data.txt')
open('C:/Users/name/data.txt')
# Absolute paths Windows/Linux
open('/home/user/data.txt')
Can also be a file descriptor:
import os
fd = os.open('data.txt', os.O_RDONLY)
open(fd, 'r')
mode
Specifies the file opening mode. If not specified, defaults to read-only mode 'r'.
| Mode | Description | When file exists | When file doesn't exist |
|---|---|---|---|
| 'r' | Read-only (default) | Opens normally | Raises FileNotFoundError |
| 'w' | Write-only | Clears file | Creates new file |
| 'x' | Exclusive write | Raises FileExistsError |
Creates new file |
| 'a' | Append | Appends at file end | Creates new file |
| 'b' | Binary | Used with other modes | |
| 't' | Text mode (default) | Used with other modes | |
| '+' | Read-write mode | Used with other modes |
Common examples:
# Text mode (default)
open('file.txt', 'r') # Read-only text
open('file.txt', 'w') # Write-only text
open('file.txt', 'a') # Append text
# Binary mode
open('image.jpg', 'rb') # Read image
open('image.jpg', 'wb') # Save image
buffering
File buffer size, defaults to -1 (system default).
encoding
File encoding, defaults to None (system default encoding).
Common encodings:
# Common encodings
open('file.txt', 'r', encoding='utf-8') # Most common
open('file.txt', 'r', encoding='gbk') # Chinese Windows
open('file.txt', 'r', encoding='gb2312') # Chinese
open('file.txt', 'r', encoding='ascii') # ASCII
open('file.txt', 'r', encoding='latin-1') # ISO-8859-1
errors
How to handle encoding errors.
# Raise error
open('file.txt', 'r', encoding='utf-8', errors='strict')
# Ignore invalid characters
open('file.txt', 'r', encoding='utf-8', errors='ignore')
# Replace with � or ?
open('file.txt', 'r', encoding='utf-8', errors='replace')
# Replace with \\xhh
open('file.txt', 'r', encoding='utf-8', errors='backslashreplace')
newline
In text mode, the newline character used when reading or writing files. Defaults to None (system default). Other options include '\n', '\r', and '\r\n'.
closefd
Whether to close the file descriptor when closing the file object. Defaults to True.
import os
# Get file descriptor
fd = os.open('data.txt', os.O_RDONLY)
print(f"File descriptor: {fd}")
# Use file descriptor
# closefd=False, Python won't close this descriptor
f = open(fd, 'r', closefd=False)
content = f.read()
f.close() # Only closes file object, not file descriptor
# File descriptor still valid
print(f"File descriptor {fd} still valid: {os.fstat(fd)}")
# Need to close manually
os.close(fd)
opener
A callable object for opening files, defaults to None. Must return a file descriptor.
import os
def custom_opener(path, flags):
print(f"Opening file: {path}, flags: {flags}")
# Must return file descriptor
return os.open(path, flags)
with open('test.txt', 'r', opener=custom_opener) as f:
pass
Return Value
The open() function returns a file object for file operations like reading and writing. After operations, use close() to close the file object and release resources.
Common file object methods:
f = open('data.txt', 'r+', encoding='utf-8')
content = f.read() # Read all content
line = f.readline() # Read one line
lines = f.readlines() # Read all lines into list
chunk = f.read(100) # Read 100 characters
f.write('hello world!\n') # Write content
f.writelines(['line1\n', 'line2\n']) # Write multiple lines
position = f.tell() # Get current file pointer position
f.seek(0) # Move to file beginning
f.seek(10) # Move to 10th byte
f.seek(0, 2) # Move to file end
f.flush() # Write buffer to disk
print(f.name) # File name
print(f.mode) # Opening mode
print(f.closed) # Whether closed
print(f.encoding) # File encoding
f.close() # Close file object
Context Manager
Use with with statement:
with open('test.txt', 'r') as f:
content = f.read()
print(content)
# No need to manually call f.close()
# Context manager handles it automatically
open() Function Examples
Read entire file at once:
# Not suitable for large files
with open('data.txt', 'r') as f:
content = f.read()
print(content)
Copy files:
# Copy image file
with open('source.jpg', 'rb') as src:
with open('copy.jpg', 'wb') as dst:
dst.write(src.read())
Process large files in chunks:
# Read large files chunk by chunk, memory-friendly
CHUNK_SIZE = 1024 * 1024 # 1MB
with open('large_file.dat', 'rb') as f:
while True:
chunk = f.read(CHUNK_SIZE)
if not chunk:
break
# Process chunk...
Read line by line using iterator, suitable for large files:
with open('data.txt', 'r') as f:
for line in f:
# Lines include newline character
print(line.strip()) # strip() removes leading/trailing whitespace
Write content to files:
# Overwrite completely
with open('data.txt', 'w') as f:
f.write('Hello, World!\n')
f.write('Second line\n')
f.writelines(['Third line\n', 'Fourth line\n']) # Write multiple lines
# Append writing
with open('log.txt', 'a') as f:
for i in range(10):
f.write(f"{i}\n")
Modify file content in binary mode:
with open('test.bin', 'r+b') as f:
# Move file pointer to 10th byte (0-indexed)
f.seek(9)
f.write(b'X') # Modify to byte 'X'