open() ファイルを開く

最終更新:2026-09-22

open() ファイルを開く

open() はファイルを開き、file オブジェクトを返す。with 文で管理することが強く推奨される。

カテゴリ組み込み関数
種類組み込み関数
Python バージョンall

📝 構文

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

⚙️ 引数

file 必須File path (str / bytes / os.PathLike) or an integer file descriptor.
mode 任意Opening mode: 'r'/'w'/'a'/'x', combinable with 'b', '+' etc.(デフォルト値:'r')
buffering 任意Buffering: 0 off, 1 line-buffered, >1 the buffer size in bytes.(デフォルト値:-1)
encoding 任意Text encoding such as 'utf-8'; defaults to the platform encoding.(デフォルト値:None)
errors 任意Encoding error handling: 'strict'/'ignore'/'replace' etc.(デフォルト値:None)
newline 任意Newline handling; None enables universal newline mode.(デフォルト値:None)
closefd 任意Whether to close the descriptor too when file is a descriptor and the file is closed.(デフォルト値:True)
opener 任意A custom opener callable that returns a file descriptor.(デフォルト値:None)

戻り値:A file object: TextIOWrapper in text mode, a BufferedIOBase subclass in binary mode.

💥 例外

▶ 例

下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:

実行結果:

hello
💡 ヒント with を使うとファイルが自動的に閉じられる;encoding を指定してプラットフォームのデフォルトエンコーディングの罠を避ける。
さらに多くのケースは近日公開予定です。

❓ よくある質問

Qwith を書かずにファイルを開くリスクは何ですか?
Aファイルが自動で閉じられず、ハンドル漏れや書き込み内容の未フラッシュが起きる可能性があります。with open(...) as f: なら途中で例外が発生しても自動的に閉じられます。
Q中国語ファイルを読むときに encoding='utf-8' を渡すのはなぜですか?
A渡さないとプラットフォームのデフォルトエンコーディング(中国語 Windows では gbk)が使われ、utf-8 ファイルと不一致で UnicodeDecodeError や文字化けになります。読み書きとも明示的に encoding を指定するのが推奨です。
Qopen() の各モード 'r'/'w'/'a'/'x' の違いは何ですか?
A'r' は読み取り専用(デフォルト。ファイルがなければ FileNotFoundError)、'w' は書き込みで元の内容を空に(なければ作成)、'a' は追記、'x' は排他的作成(既存なら FileExistsError)です。
Qバイナリファイルを開くにはどうしますか?
Amode に 'b' を付けます:open('img.png', 'rb') はバイトを読み、open('img.png', 'wb') はバイトを書きます。バイナリモードでは encoding 引数を渡せません。
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%