open()

Open a file. Almost always use it with `with` — Python will close for you.

Built-in functionPython 1.0+
Common call
with open(path, "r", encoding="utf-8") as f: text = f.read()
Returns
a file object — str in text mode, bytes in binary mode
Replaces
the older os.open + os.read + os.close low-level API
Watch out
use `with` to guarantee close; specify encoding on text mode; "w" truncates
open(filefileThe path to open, or an integer file descriptor. Accepts str, bytes, os.PathLike, or an fd.type: str | Path | int · required, modemodeMode string. Combinations of r (read) / w (write, truncates) / a (append) / x (create-exclusive) / + (read AND write) and b (binary) / t (text, default).type: str · default: "r"='r', bufferingbufferingBuffering policy. -1 uses the default; 0 for unbuffered (binary only); 1 for line-buffered.type: int · default: -1=-1, encodingencodingText mode only. utf-8 is a good default; None uses the locale-dependent default which is fragile.type: str · default: None=None, errorserrorsHow to handle encoding errors: strict (default), ignore, replace, backslashreplace, ...type: str · default: None=None, newlinenewlineNewline handling. None enables universal newlines; "" disables translation.type: str · default: None=None, closefd=True, opener=None)
file object

Parameters

NameTypeRequiredDescription
filestr | Path | intyesThe path to open, or an integer file descriptor. Accepts str, bytes, os.PathLike, or an fd.
modestrno ("r")Mode string. Combinations of r (read) / w (write, truncates) / a (append) / x (create-exclusive) / + (read AND write) and b (binary) / t (text, default).
encodingstrno (None)Text mode only. utf-8 is a good default; None uses the locale-dependent default which is fragile.
errorsstrno (None)How to handle encoding errors: strict (default), ignore, replace, backslashreplace, ...
newlinestrno (None)Newline handling. None enables universal newlines; "" disables translation.
bufferingintno (-1)Buffering policy. -1 uses the default; 0 for unbuffered (binary only); 1 for line-buffered.

Return value

file objectA file object supporting read / write / iteration / seek. In TEXT mode returns a TextIOWrapper (str); in BINARY mode returns a BufferedReader / BufferedWriter (bytes). Always use `with open(...) as f:` so the file is closed on exit.

Common patterns

Read a text file (utf-8)
Always specify encoding — the default is locale-dependent.
with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()
Write a text file
"w" TRUNCATES on open — be sure you meant it.
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
Append (do not truncate)
Add lines without erasing the existing content.
with open("log.txt", "a", encoding="utf-8") as f:
    f.write(line + "\n")
Read binary
For images, protocols, anything not text.
with open("photo.jpg", "rb") as f:
    data = f.read()
Iterate line by line
File objects are iterators of lines — memory-friendly for large files.
with open("big.log", "r", encoding="utf-8") as f:
    for line in f:
        process(line)
Create-if-missing, refuse-if-exists
"x" mode — safer than "w" when you must not overwrite.
with open("unique.txt", "x", encoding="utf-8") as f:
    ...

Examples

1. Read all
with open("f.txt", encoding="utf-8") as f: text = f.read()
Returns
file contents as str
2. Read lines
with open("f.txt", encoding="utf-8") as f: lines = f.readlines()
Returns
list of str
3. Write
with open("f.txt", "w", encoding="utf-8") as f: f.write("hi")
Returns
file created / overwritten
4. Append
with open("f.txt", "a", encoding="utf-8") as f: f.write("more\n")
Returns
appended
5. Read binary
with open("img.png", "rb") as f: data = f.read()
Returns
bytes
6. Missing file
open("nope.txt", "r")
Returns
FileNotFoundError
7. Existing + x
open("existing.txt", "x")
Returns
FileExistsError

Pitfalls

1. Not using `with` — file may leak until GC
A raw `open()` without `with` relies on the garbage collector to close the file. CPython usually closes promptly, but the exact timing is implementation-dependent (PyPy and some patterns delay it). Always use `with`.
Leaked
f = open("data.txt")
text = f.read()   # forgot to close
file stays open
Use with
with open("data.txt") as f:
    text = f.read()
closed on exit
2. "w" TRUNCATES on open — before you write anything
The truncation happens the moment open() returns. Even if your subsequent write fails, the original data is gone. Use "a" for append, "r+" for read-then-modify, "x" to refuse-if-exists.
Data loss
with open("valuable.txt", "w") as f:
    raise SomeError()   # file now empty
file truncated
Match intent
open(path, "a")   # or "r+" or "x"
preserves data
3. Text mode uses the LOCALE encoding by default — fragile
On some systems the default is cp1252 or ANSI; on Linux it is often UTF-8. If you don't specify encoding, the same code reads differently on different machines. ALWAYS pass encoding.
Locale-dependent
open("data.txt")   # what encoding?
varies by OS/locale
Explicit UTF-8
open("data.txt", encoding="utf-8")
portable
4. Binary mode returns BYTES, text mode returns STR
Mixing them causes TypeErrors. Reading a text file in "rb" gives bytes; writing str to a "wb" file fails. Pick the mode that matches the data.
Type mismatch
with open("f", "wb") as f:
    f.write("hi")
TypeError: a bytes-like object is required, not 'str'
Match the mode
f.write(b"hi")
or open in text mode

When to use

Use it
  • Reading and writing files — always through `with`
  • Iterating lines of a large file without loading it all
  • Binary I/O for images, protocols, non-text data
  • Any file operation — this is the canonical builtin
Reach for something else
  • Complex path manipulation → pair with pathlib.Path
  • Very high-throughput I/O → consider mmap or lower-level APIs
  • Reading structured data → prefer csv / json / a real parser
  • Network I/O disguised as file I/O → use the right module (urllib, requests, ...)

Notes

Complexity
O(1) to open; O(n) to read
Return
A file object; use as a context manager
CPython impl
Python/bltinmodule.c :: builtin_open — dispatches to io.open
Memory
Allocates buffered wrapper objects
Thread-safe
File objects are not safe for concurrent access

FAQ

To guarantee the file is closed as soon as the block exits — even on exceptions. Without `with`, you rely on the garbage collector, whose timing is implementation-dependent.

History

1.0
open() has been a builtin since Python 1.0.
3.0
Text vs binary mode enforced; text returns str, binary returns bytes.
3.3
"x" mode added for exclusive creation.
3.15
PEP 686 — UTF-8 becomes the default encoding.