Python Reference ยท Files, Paths and Text I/O
open() modes and encodings
Reference for the open() mode string in Python: r, w, a, x, b, t and +, plus the encoding, errors and newline arguments, with runnable examples.
The second argument of open() is a mode string that says whether you read, write or append, and whether the file holds text or raw bytes. Three keyword arguments, encoding, errors and newline, control how text is translated to and from bytes on disk.
Getting these right prevents the classic surprises: a file that was emptied because you opened it with "w", text that looks garbled because the encoding was guessed wrong, or an extra blank line after every row on Windows.
with open("notes.txt", "w", encoding="utf-8") as f: f.write("hello\n")
Try it
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.
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
open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None)
| Mode letter | Meaning |
|---|---|
r |
Read (default). The file must exist. |
w |
Write. Creates the file, or empties it if it exists. |
a |
Append. Creates the file if needed; writes always go to the end. |
x |
Create exclusively. Raises FileExistsError if the file exists. |
+ |
Add the other direction: r+ reads and writes without emptying; w+ empties first; a+ reads and appends. |
t |
Text mode (default). You read and write str. |
b |
Binary mode. You read and write bytes (or bytearray). |
Letters combine: "rb", "wb", "a+", "r+b". Exactly one of r, w, a or x must be present.
| Name | Description |
|---|---|
encoding |
Text only. How characters become bytes, such as "utf-8". Default depends on the system. |
errors |
Text only. What to do with undecodable bytes: "strict" (default), "replace", "ignore", "backslashreplace". |
newline |
Text only. Controls line-ending translation: None (default), "", "\n", "\r" or "\r\n". |
buffering |
-1 for the default, 0 (binary only) for unbuffered, 1 for line buffering (text), or a buffer size in bytes. |
Return value: a file object: TextIOWrapper in text mode, BufferedReader or BufferedWriter in binary mode.
Raises: FileNotFoundError, FileExistsError, PermissionError, IsADirectoryError (all subclasses of OSError), ValueError for an invalid mode, and UnicodeDecodeError or UnicodeEncodeError while reading or writing text.
Usage notes
- Always pass
encodingfor text. Without it Python uses the platform's default, which differs between machines.encoding="utf-8"makes your program behave the same everywhere. (Python 3.15 is planned to make UTF-8 the default, but explicit is still clearer.) "w"destroys existing content the moment the file is opened, before you write anything. Use"x"if overwriting would be a bug, or"a"to add.- Newlines. With
newline=None, reading turns\r\nand\rinto\n, and writing turns\ninto the platform's line ending. Withnewline="", no translation happens; use that for thecsvmodule, which does its own handling. - Binary mode ignores encodings and newlines. Passing
encoding,errorsornewlinetogether with"b"raisesValueError. - Wrong-but-silent decodes. Single-byte encodings such as
latin-1never fail: they turn any bytes into characters. That hides the mistake rather than fixing it. - Close files. Use
with open(...) as f:so the file closes (and buffered data is flushed) even when an error occurs. - Lines vs. characters. In text mode,
seek()andtell()positions are opaque numbers, not character counts. Seeseek()andtell(). - Paths.
filecan be a string, apathlib.Path, or an integer file descriptor.