Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python open() function

Reference for Python open(): modes, encoding, newline, with statement, reading and writing text and binary files, common errors and best practices.

The built-in open() function opens a file and returns a file object that you can read from, write to or iterate over line by line. What kind of object you get depends on the mode: text mode returns a TextIOWrapper that works with str, binary mode returns a buffered object that works with bytes.

Always close what you open. The safest way is a with block, which closes the file for you even if an error occurs. In text mode, always pass encoding="utf-8" explicitly, because the default depends on the operating system and settings.

Python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

Try it

The runner has an in-memory file system, so files exist only during one run.

Python Write, append and read

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Binary mode, exclusive creation and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
open(file, mode="r", buffering=-1, encoding=None,
     errors=None, newline=None, closefd=True, opener=None)
Name Description
file Path as a str, bytes or pathlib.Path (or an integer file descriptor).
mode Combination of the letters below. Default "r" (read text).
buffering 0 (binary only, unbuffered), 1 (line buffered, text only) or a buffer size. -1 picks a default.
encoding Text encoding such as "utf-8". Text mode only.
errors How to treat encoding errors: "strict" (default), "replace", "ignore", ...
newline Controls line-ending translation: None, "", "\n", "\r" or "\r\n".
closefd If False, an integer file descriptor stays open after the file object closes.
opener Custom callable returning a file descriptor. Rarely needed.

Modes:

Mode Meaning
r Read (default). The file must exist.
w Write. Creates the file or truncates it to empty.
a Append. Creates the file if needed; writes always go to the end.
x Create exclusively. Fails if the file already exists.
+ Add reading and writing, for example r+ or w+.
t / b Text (default) or binary.

Return value: a file object (TextIOWrapper, BufferedReader, BufferedWriter or BufferedRandom).

Raises: FileNotFoundError, FileExistsError (mode x), PermissionError, IsADirectoryError, ValueError for an invalid mode, UnicodeDecodeError when reading with the wrong encoding.

Usage notes

  • Use with. Without it, data may stay in a buffer and never reach the disk if the program ends unexpectedly, and handles leak.
  • "w" destroys existing content immediately on open, before you write anything. Use "x" when overwriting would be a bug.
  • Always give encoding in text mode. Otherwise the default depends on the platform (and on UTF-8 mode), which makes code behave differently across machines.
  • Binary mode returns bytes. Do not pass encoding or newline there; it raises ValueError.
  • Iterating a file yields one line at a time, with the trailing \n, and uses little memory for huge files. read() loads everything.
  • Newlines. In text mode, \n is translated to and from the platform line ending. Pass newline="" when reading or writing CSV files.
  • The cursor moves with reads and writes. Use tell() and seek() to inspect and move it; after writing in w+, seek to 0 before reading back.
  • Relative paths are relative to the current working directory, not to the script's folder. pathlib.Path(__file__).parent is a safer anchor.
  • pathlib offers Path.read_text(), write_text() and open() as friendlier shortcuts for small files.
  • Closed files raise ValueError: I/O operation on closed file on any use.