Python 3 reference · Built-in Functions
Python open() Function
Open a file and return a file object for reading or writing text or bytes. Use it in a with block so it closes automatically.
Python 3 Since 3.0
Syntax
open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameters
| Parameter | Description |
|---|---|
file |
A path (string or pathlib.Path) or a file descriptor. |
mode optional |
"r" read, "w" write (truncate), "a" append, "x" create; add "b" for binary or "+" for read/write. Default: "r" |
encoding optional |
Text encoding, e.g. "utf-8". UTF-8 is the default since Python 3.15. |
buffering, errors, newline, closefd, opener optional |
Advanced options. |
Return value
A file object (text or binary depending on the mode).
Examples
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.rstrip())
Output
first line second line
with open("log.txt", "w") as f:
f.write("start\n")
with open("log.txt", "a") as f:
f.write("more\n")
print(open("log.txt").read())
Output
start more
with open("data.bin", "wb") as f:
f.write(bytes([1, 2, 255]))
with open("data.bin", "rb") as f:
print(f.read())
Output
b'\x01\x02\xff'
Common mistakes
- Always use
with open(...) as f:so the file is closed even if an error happens. - Mode
"w"erases the file first. Use"a"to add to it, or"x"to fail if it already exists. - Before Python 3.15 the default encoding depended on the operating system (often not UTF-8 on Windows); pass
encoding="utf-8"explicitly for portable code. - Examples here use an in-memory file system, so the files disappear after the run.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.15 | UTF-8 is the default encoding when encoding isn't given (PEP 686). |
Related
print()· Write values to standard output (or a file), separated by spaces and followed by a newline. Both are configurable.input()· Read a line of text typed by the user, after printing an optional prompt. The result is always a string.bytes()· Create an immutable sequence of bytes: raw binary data such as file contents, network messages or encoded text.- Python File Handling · tutorial