On this page
open
Prev: oct | Up: __builtins__ | Next: ord
Rel: breakpoint, compile, eval, exec, globals
Ref: docs.python.org — open
Tags: #public #python3 #builtins
Import & Availability
# Built-in (available globally without import)
from builtins import open
Overview & Signature
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
Usage
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "hello.txt"
with open(p, "w", encoding="utf-8") as f:
f.write("line 1\n")
with open(p, "r", encoding="utf-8") as f:
assert f.read() == "line 1\n"
Gotchas
- Always use
with open(...) as f:and passencoding="utf-8"for text files so Windows/Unix behavior matches. - Use
newline=""when opening files for thecsvmodule.
REPL Inspect
help(open)
Linked from
Related notes
- tuts/python3/__builtins__/__builtins__ Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/oct Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/ord Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__ links to this page; shared tags: #builtins
- tuts/python3/__builtins__/breakpoint Linked here; shared tags: #builtins
- tuts/python3/__builtins__/compile Linked here; shared tags: #builtins
- tuts/python3/__builtins__/eval Linked here; shared tags: #builtins
- tuts/python3/__builtins__/exec Linked here; shared tags: #builtins
- tuts/python3/__builtins__/globals Linked here; shared tags: #builtins
- tuts/python3 links to this page