Python open function
last modified November 29, 2026 Python 3.15
In this article we show how to use the built-in open function to
work with files in Python. We look at the call signature, the file modes, text
and binary data, encoding and newline handling, buffering, and the errors that
open can raise.
Reading a file's contents, reading it line by line, writing, closing, and moving the file pointer each have their own article. This text concentrates on opening the file correctly.
Opening a file
The open function takes a path and a mode and returns a file
object. The object is the handle through which all reading and writing goes.
The full signature has several optional parameters, most of which have sensible
defaults.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
The file is a path as a string, and mode says how the
file is opened. The remaining parameters control buffering, text decoding,
newline translation, and how the underlying file descriptor is created. They
are described in the sections below.
The file object should be closed when it is no longer needed. The usual way is
the with statement, which closes the file even when the block
raises an exception.
with open('greeting.txt', 'w', encoding='utf-8') as f:
f.write('Hello there!\n')
f.write('This file was written by Python.\n')
with open('greeting.txt', encoding='utf-8') as f:
print(f.read(), end='')
print(f.closed)
The first block creates the file and writes two lines. The mode 'w'
truncates an existing file, so the program produces the same file on every run.
The second block opens the file for reading, the default mode. The
end='' argument prevents print from adding another
newline, because the file lines already end with one.
After each with block the file is closed, but the variable
f still refers to the closed object, which is why
f.closed is True at the end.
$ python opening.py Hello there! This file was written by Python. True
The file object
The type of the returned object depends on the mode. A text file gives a
TextIOWrapper, and a binary file gives a buffered reader or writer
(or a raw stream when buffering is disabled). All of them share a few
attributes and methods that describe the stream.
with open('sample.txt', 'w', encoding='utf-8') as f:
print(f.name, f.mode, f.encoding)
print(f.readable(), f.writable(), f.seekable())
print(f.closed)
The name attribute holds the path, mode the mode
string, and encoding the codec used for text. The three test
methods say what the stream supports: this file is writable and seekable but
not readable. After the block, closed becomes True.
$ python file_object.py sample.txt w utf-8 False True True True
File modes
The mode consists of one basic character and optional modifiers. Exactly one of the four basic modes must be present.
| Mode | Meaning |
|---|---|
| 'r' | open for reading (default); the file must exist |
| 'w' | open for writing, truncating the file first |
| 'x' | create a new file and open it for writing; fail if it exists |
| 'a' | open for writing, appending to the end of the file |
| 'b' | binary mode |
| 't' | text mode (default) |
| '+' | open for updating (reading and writing) |
The modifiers combine with the basic mode: 'rb' reads bytes,
'w+' reads and writes, and 'a+' appends and reads.
The 'b' and 't' modifiers cannot be used together.
Writing modes differ in what happens to an existing file. 'w'
empties it, 'a' keeps it and writes at the end, and
'x' refuses to touch it.
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('first note\n')
with open('notes.txt', 'a', encoding='utf-8') as f:
f.write('second note\n')
try:
open('notes.txt', 'x').close()
except FileExistsError as e:
print(type(e).__name__, e.errno, e.filename)
with open('notes.txt', encoding='utf-8') as f:
print(f.read(), end='')
The first block creates the file, and the second one appends to it, so both
notes are present. The third block asks for exclusive creation and fails with
FileExistsError, whose errno is 17 and whose
filename names the file. This is the safe way to create a file
only when it does not exist yet.
$ python modes.py FileExistsError 17 notes.txt first note second note
Binary mode
In binary mode the file object deals in bytes, not
str. No decoding, encoding, or newline translation takes place, so
the bytes read are exactly the bytes stored.
with open('data.bin', 'wb') as f:
print(f.mode)
print(f.write(b'\x00\x01\x02\xff'))
with open('data.bin', 'rb') as f:
data = f.read()
print(data)
print(list(data))
The write method returns the number of bytes written, here 4. The
same bytes come back from read as a bytes object, and
converting it to a list shows the individual byte values, including 255 for
\xff.
$ python binary.py wb 4 b'\x00\x01\x02\xff' [0, 1, 2, 255]
Encoding
A text file stores bytes, but the program works with characters. The encoding
tells Python how to convert between the two. Since Python 3.15, UTF-8 mode is
enabled by default (PEP 686), so open uses UTF-8 when no encoding
is given. In 3.14 and earlier the locale encoding is used, which is not always
UTF-8, so passing encoding explicitly keeps a program portable.
The errors parameter decides what happens when a byte sequence
cannot be decoded: 'strict' (the default) raises
UnicodeDecodeError, 'ignore' drops the offending
bytes, and 'replace' puts a replacement character in their place.
text = 'Zürich, César, 東京'
with open('names.txt', 'w', encoding='utf-8') as f:
f.write(text)
with open('names.txt', encoding='utf-8') as f:
print(f.read())
with open('names.txt', encoding='ascii', errors='ignore') as f:
print(f.read())
try:
with open('names.txt', encoding='ascii') as f:
f.read()
except UnicodeDecodeError as e:
print(e.encoding, e.start, e.end, e.reason)
The file is written and read back as UTF-8, so all three names survive. ASCII
cannot represent any character above 127, so the 'ignore' policy
silently removes those bytes and leaves Zrich, Csar,. The default
strict policy raises UnicodeDecodeError instead; its attributes
give the codec, the byte range, and the reason for the failure.
$ python encoding.py Zürich, César, 東京 Zrich, Csar, ascii 1 2 ordinal not in range(128)
Newlines
Text mode translates line endings. On reading, \r\n and
\r both become \n, which is called universal newline
mode. On writing, \n is translated to the platform line separator.
The newline parameter changes this behaviour: ''
disables translation in both directions, while '\n',
'\r', or '\r\n' selects a specific terminator.
with open('lines.txt', 'w', newline='', encoding='utf-8') as f:
f.write('alpha\r\nbeta\r\ngamma\r\n')
with open('lines.txt', encoding='utf-8') as f:
print(repr(f.read()))
with open('lines.txt', encoding='utf-8', newline='') as f:
print(repr(f.read()))
The file is written with Windows line endings and no translation. The default
read translates each \r\n to \n. The last read passes
newline='' and keeps the original \r\n sequences. Use
newline='' when the exact line endings matter, for example when
comparing or copying files.
$ python newlines.py 'alpha\nbeta\ngamma\n' 'alpha\r\nbeta\r\ngamma\r\n'
Buffering and flushing
By default the file is buffered: writes go to an in-memory buffer and reach the
disk in larger blocks. buffering=0 turns buffering off and is
allowed only in binary mode. buffering=1 selects line buffering in
text mode, so every newline flushes the buffer.
with open('todo.txt', 'w', buffering=1, encoding='utf-8') as f:
print(f.line_buffering)
print(f.write('milk\n'))
print(f.write('bread\n'))
f.flush()
with open('todo.txt', encoding='utf-8') as f:
print(f.read(), end='')
The line_buffering attribute confirms that line buffering is
active, and each write returns the number of characters written,
5 and 6. flush forces the buffer to the file even before the block
ends; closing the file does the same. No data was lost, so the second block
reads both lines.
$ python buffering.py True 5 6 milk bread
Reading and writing in one file
A mode with '+' opens the file for both reading and writing.
'w+' truncates the file first, while 'r+' requires an
existing file and keeps its contents. After writing, the file pointer sits at
the end, so you must move it back with seek before reading.
with open('counter.txt', 'w+', encoding='utf-8') as f:
f.write('one\ntwo\nthree\n')
f.seek(0)
print(f.readline(), end='')
print(f.read(3))
print(f.tell())
The file is written, then rewound to the beginning. readline
consumes one\n, and read(3) takes the next three
characters, two. The pointer has moved seven bytes from the start,
which tell reports. The pointer, seek, and
tell are covered in their own articles.
$ python read_write.py one two 7
Errors
Failures to open a file are reported as exceptions from the OSError
family. Each carries an errno code and usually the offending
filename, which makes detailed error messages possible.
try:
open('missing.txt')
except FileNotFoundError as e:
print(type(e).__name__, e.errno, e.filename)
try:
open('.')
except IsADirectoryError as e:
print(type(e).__name__, e.errno)
with open('readonly.txt', 'w') as f:
f.write('data')
try:
with open('readonly.txt') as f:
f.write('more')
except OSError as e:
print(type(e).__name__, e)
The missing file raises FileNotFoundError with errno 2, and on
Linux opening a directory raises IsADirectoryError with errno 21
(Windows reports PermissionError instead). The last block tries to
write to a file opened for reading, which raises
UnsupportedOperation, a subclass of both OSError and
ValueError. Catching OSError covers all of these
cases.
$ python errors.py FileNotFoundError 2 missing.txt IsADirectoryError 21 UnsupportedOperation not writable
Common mistakes
Most problems with open come from a few habits. Keep the following
in mind.
- Leaving files open. Without
withor an explicitclose, the file may stay open until the garbage collector runs, and unflushed data can be lost. - Using text mode for binary data. Decoding an image or an archive usually
fails with
UnicodeDecodeError, and writing text mode can change line endings and corrupt the file. - Forgetting that
writedoes not add a newline. Unlikeprint, it writes exactly the characters it is given. - Reading after writing without
seek. The pointer is at the end, soreadreturns an empty string. - Relying on the default encoding. Pass
encoding='utf-8'in code that must run on Python 3.14 and earlier as well.
Source
open – Built-in Functions – Python documentation
io – Core tools for working with streams – Python documentation
PEP 686 – Make UTF-8 mode default
In this article we have opened text and binary files, chosen modes and encodings, controlled newline translation and buffering, and handled errors. See also Python read file, Python read text, Python write function, Python close function, Python seek function, and Python context managers.
Author
List all Python tutorials.