open()

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Returns: TextIOWrapper | BufferedReader | BufferedWriter | IO · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
file io built-in filesystem read write

The open() function is the primary way to work with files in Python. It opens a file (or creates one) and returns a file object that you can use to read, write, or modify the file’s contents. This is one of the most frequently used built-in functions in Python, essential for any file operations.

Syntax

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameters

ParameterTypeDefaultDescription
filestr | bytes | int | PathA file path (string or bytes), a file descriptor (integer), or a path-like object. When an integer is provided, it’s treated as a file descriptor.
modestr'r'Specifies how the file will be opened. Common values: 'r' (read), 'w' (write, truncates), 'a' (append), 'x' (exclusive creation). Can combine with 'b' (binary), 't' (text), or '+' (update).
bufferingint-1Controls buffering. -1 (default) uses system default; 0 disables buffering (binary mode only); 1 enables line buffering (text mode); values > 1 set buffer size in bytes.
encodingstr | NoneNoneThe text encoding to use (e.g., 'utf-8', 'latin-1', 'ascii'). Only applicable in text mode. Default is platform-dependent.
errorsstr | NoneNoneSpecifies how encoding/decoding errors are handled. Common values: 'strict' (raise exception), 'ignore', 'replace', 'backslashreplace'.
newlinestr | NoneNoneControls how universal newlines work. None (default) enables universal newlines; '' disables translation; '\n', '\r', '\r\n' specify explicit line endings.
closefdboolTrueIf True, close the underlying file descriptor when the file is closed. Must be True when file is a path (not allowed to be False).
openercallable | NoneNoneA custom opener function that receives (path, flags) and returns a file descriptor. The os.open() flags determine file open mode.

Returns: A file object. The actual type depends on the mode—TextIOWrapper for text mode, BufferedReader/BufferedWriter/BufferedRandom for binary mode.

Examples

Reading a text file

The most common use case is opening a file for reading:

# Read entire file content
with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)

# Read lines one by one
with open('example.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())

Writing to a file

Use mode 'w' to create a new file or overwrite an existing one:

# Write text to a file
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!\n')
    f.write('Second line\n')

# Write multiple lines at once
lines = ['Line 1', 'Line 2', 'Line 3']
with open('multipline.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(lines))

Appending to a file

Use mode 'a' to add content to the end of an existing file:

# Append to existing file
with open('log.txt', 'a', encoding='utf-8') as f:
    f.write('New log entry\n')

Binary mode

Use 'b' mode for binary files (images, audio, etc.):

# Read binary data
with open('image.png', 'rb') as f:
    data = f.read()

# Write binary data
with open('copy.png', 'wb') as f:
    f.write(data)

Reading and writing with ’+’ mode

The '+' modifier allows both reading and writing:

# Read and modify content
with open('file.txt', 'r+', encoding='utf-8') as f:
    content = f.read()
    f.seek(0)  # Go back to beginning
    f.write(content.upper())

Using different encodings

Handle files with specific text encodings:

# Read UTF-8 encoded file
with open('utf8_file.txt', 'r', encoding='utf-8') as f:
    text = f.read()

# Read Latin-1 encoded file
with open('latin1_file.txt', 'r', encoding='latin-1') as f:
    text = f.read()

# Handle encoding errors gracefully
with open('messy_file.txt', 'r', encoding='utf-8', errors='replace') as f:
    text = f.read()

Using a custom opener

For special file permissions, use a custom opener:

# Open with specific permissions using os.open
import os

def custom_opener(path, flags):
    return os.open(path, flags, 0o644)

with open('file.txt', 'w', opener=custom_opener) as f:
    f.write('Content with custom permissions')

Working with file descriptors

You can also open using a file descriptor:

import os

# Open file descriptor directly
fd = os.open('file.txt', os.O_RDONLY)
with os.fdopen(fd, 'r', encoding='utf-8') as f:
    content = f.read()

Common Patterns

Always use with statements to ensure files are properly closed:

# Safe: file is closed even if an exception occurs
with open('file.txt', 'r') as f:
    data = f.read()
# File is now closed

Reading large files line by line

For memory efficiency with large files:

# Process large file line by line
with open('huge_file.txt', 'r') as f:
    for line in f:
        process(line)

Checking if file exists before writing

Avoid accidentally overwriting:

import os

filename = 'important.txt'
if os.path.exists(filename):
    print(f'{filename} already exists')
else:
    with open(filename, 'w') as f:
        f.write('New content')

Errors

FileNotFoundError

Raised when trying to read a file that doesn’t exist:

open('nonexistent.txt', 'r')
# FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'

PermissionError

Raised when lacking permission to access the file:

open('/root/secret.txt', 'r')
# PermissionError: [Errno 13] Permission denied: '/root/secret.txt'

IsADirectoryError

Raised when trying to open a directory as a file:

open('/home', 'r')
# IsADirectoryError: [Errno 21] Is a directory: '/home'

ValueError for invalid modes

Raised when using an invalid mode string:

open('file.txt', 'z')
# ValueError: invalid mode: 'z'

Unsupported operations in mode

Attempting operations not allowed by the mode:

# Read from write-only file
with open('file.txt', 'w') as f:
    f.read()
# io.UnsupportedOperation: not readable

See Also