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.

CategoryBuilt-in Functions
KindBuilt-in Function
Python Versionall

📝 Syntax

open(file, mode='r', ...)

⚙️ Parameters

file RequiredFile path (str / bytes / os.PathLike) or an integer file descriptor.
mode OptionalOpening mode: 'r'/'w'/'a'/'x', combinable with 'b', '+' etc.(Default:'r')
buffering OptionalBuffering: 0 off, 1 line-buffered, >1 the buffer size in bytes.(Default:-1)
encoding OptionalText encoding such as 'utf-8'; defaults to the platform encoding.(Default:None)
errors OptionalEncoding error handling: 'strict'/'ignore'/'replace' etc.(Default:None)
newline OptionalNewline handling; None enables universal newline mode.(Default:None)
closefd OptionalWhether to close the descriptor too when file is a descriptor and the file is closed.(Default:True)
opener OptionalA 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

▶ 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏