open() Open file
Last updated: 2026-09-22
open() Open file
open() opens a file and returns a file object. Strongly recommended to use a `with` statement.
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
open(file, mode='r', ...)
⚙️ Parameters
| file Required | File path (str / bytes / os.PathLike) or an integer file descriptor. |
|---|---|
| mode Optional | Opening mode: 'r'/'w'/'a'/'x', combinable with 'b', '+' etc.(Default:'r') |
| buffering Optional | Buffering: 0 off, 1 line-buffered, >1 the buffer size in bytes.(Default:-1) |
| encoding Optional | Text encoding such as 'utf-8'; defaults to the platform encoding.(Default:None) |
| errors Optional | Encoding error handling: 'strict'/'ignore'/'replace' etc.(Default:None) |
| newline Optional | Newline handling; None enables universal newline mode.(Default:None) |
| closefd Optional | Whether to close the descriptor too when file is a descriptor and the file is closed.(Default:True) |
| opener Optional | A custom opener callable that returns a file descriptor.(Default:None) |
Returns:A file object: TextIOWrapper in text mode, a BufferedIOBase subclass in binary mode.
💥 Raises
OSError— Raised (including subclasses like FileNotFoundError) when the file cannot be opened.ValueError— Raised when mode is invalid or the mode/encoding combination conflicts.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
hello
💡 Tip Use `with` to close the file automatically; always set encoding explicitly.
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the risk of opening a file without with?
AThe file may not be closed automatically, causing a handle leak or unflushed writes; using with open(...) as f: closes it automatically even when an exception is raised midway.
QWhy pass encoding='utf-8' when reading Chinese files?
AWithout it, the platform default encoding is used (gbk on Chinese Windows), which mismatches utf-8 files and raises UnicodeDecodeError or produces garbled text; it is recommended to specify encoding explicitly for both reads and writes.
QWhat is the difference between the 'r'/'w'/'a'/'x' modes of open()?
A'r' is read-only (the default; raises FileNotFoundError if the file does not exist), 'w' writes and clears the original content (creating the file if missing), 'a' appends, and 'x' creates exclusively (raising FileExistsError if it already exists).
QHow do I open a binary file?
AAdd 'b' to the mode: open('img.png', 'rb') reads bytes and open('img.png', 'wb') writes bytes; binary mode does not accept the encoding parameter.