The built-in open() function opens a file and returns a file object you can read from or write to. Its main arguments are the path and a mode string such as "r" (read), "w" (write, truncating), "a" (append) or "x" (create exclusively). Always open files with a with statement so they are closed automatically, and pass encoding="utf-8" for text files.
open()open() with the with statementpathlibopen()The full signature is:
The arguments you use most often are these.
file is a path as a string or a pathlib.Path, or an integer file descriptor.mode selects reading, writing or appending, and text or binary.encoding names the text encoding. If omitted, Python uses a locale-dependent default, which differs between machines. Always set it explicitly for text.errors controls what happens on bad bytes, for example "replace" or "ignore".newline controls newline translation in text mode.| Mode | Meaning | If the file does not exist |
|---|---|---|
r | Read (default) | FileNotFoundError |
w | Write, truncating existing content | Created |
a | Append to the end | Created |
x | Create and write, fail if it exists | Created |
r+ | Read and write, no truncation | FileNotFoundError |
w+ | Read and write, truncating | Created |
b suffix | Binary mode, such as rb or wb | Same as base mode |
t suffix | Text mode (default) | Same as base mode |
In text mode you read and write str and Python decodes and encodes using the given encoding. In binary mode you read and write bytes and no translation happens. A missing file in "r" mode raises FileNotFoundError, a subclass of OSError (and IOError is just an alias of OSError in Python 3).
open() with the with statementA file object holds an operating-system resource, so it must be closed. The with statement closes it even when an exception occurs.
Without with, you would have to call f.close() in a finally block. Forgetting this can leave data unflushed and, on some systems, exhaust the limit of open files.
Choose the reading method that matches the file size.
read() returns the whole file as one string, so avoid it for very large files.readline() returns one line, including the newline character.readlines() returns a list of all lines."w" replaces the content of an existing file immediately when opened. Use "a" to add to the end, and "x" to refuse to overwrite.
writelines() does not add newline characters, so include them in your strings.
pathlibUse "rb" and "wb" for images, archives and any non-text data.
Path.open() takes the same arguments as the built-in, and Path.read_text() and Path.write_text() are short forms for small text files:
Reading in fixed-size chunks keeps memory use constant regardless of the file size.
Opening a file can fail for several reasons, and each has its own exception.
Catch the specific exception you can handle, and let others propagate.
with open() instead of open() and close()?with guarantees the file is closed even when an error occurs, and it flushes buffered output. It is the recommended way in all current Python versions.
w and a mode?w empties an existing file as soon as it is opened. a keeps the existing content and writes new data at the end.
For text files, yes. The default depends on the system locale, so code that works on one machine may fail or corrupt text on another. Use utf-8 unless the format demands otherwise.
Iterate over the file object line by line, or read fixed-size chunks with read(size).
open() returns a file object for reading, writing or appending. Pick the right mode, set encoding="utf-8" for text, use with to close the file, read big files line by line or in chunks, and catch specific errors such as FileNotFoundError. Use pathlib.Path for convenient path handling.