組み込み関数 open で Shift-JIS のファイルを開く方法
open関数の引数に encoding='shift_jis' を追加します。次のコードは 組み込み関数open() を使用し、Shift-JIS のファイルを開きます。
# 組み込み関数open() で Shift-JIS のファイルを開く
with open(file='shift-jis.txt', encoding='shift_jis') as file:
text = file.read()
pathlib で Shift-JIS のファイルを開く方法
openメソッドの引数に encoding='shift_jis' を指定します。次のコードは pathlib を使用し、Shift-JIS のファイルを開きます。
from pathlib import Path
# Path オブジェクトを生成
sjisFilePath = Path('shift-jis.txt')
# pathlib で Shift-JIS のファイルを開く
with sjisFilePath.open(encoding='shift_jis') as file:
text = file.read()
print(text)
encoding に指定できる日本語に対応したコーデック
全てのコーデックはPython公式ドキュメントを参照してください。| encoding | 別名 |
|---|---|
| cp932 | 932, ms932, mskanji, ms-kanji |
| euc_jp | eucjp, ujis, u-jis |
| euc_jis_2004 | jisx0213, eucjis2004 |
| euc_jisx0213 | eucjisx0213 |
| iso2022_jp | csiso2022jp, iso2022jp, iso-2022-jp |
| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 |
| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 |
| iso2022_jp_2004 | iso2022jp-2004, iso-2022-jp-2004 |
| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 |
| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext |
| shift_jis | csshiftjis, shiftjis, sjis, s_jis |
| shift_jis_2004 | shiftjis2004, sjis_2004, sjis2004 |
| shift_jisx0213 | shiftjisx0213, sjisx0213, s_jisx0213 |
| utf_32 | U32, utf32 |
| utf_32_be | UTF-32BE |
| utf_32_le | UTF-32LE |
| utf_16 | U16, utf16 |
| utf_16_be | UTF-16BE |
| utf_16_le | UTF-16LE |
| utf_7 | U7, unicode-1-1-utf-7 |
| utf_8 | U8, UTF, utf8, cp65001 |
| utf_8_sig | 無し |
サンプルコードの実行結果


参考資料
- Python公式ドキュメント - 組み込み関数 open()
- Python公式ドキュメント - pathlib Path.open()
- Python公式ドキュメント - codecs 標準エンコーディング
検証環境
- Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 21H2 OS Build 19044.2130 Experience: Windows Feature Experience Pack 120.2212.4180.0