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.
💥 例外
OSError— Raised (including subclasses like FileNotFoundError) when the file cannot be opened.ValueError— Raised when mode is invalid or the mode/encoding combination conflicts.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
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 引数を渡せません。