Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active April 5, 2016 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/152eacd23b793ecd3dbf5f706ae33e92 to your computer and use it in GitHub Desktop.
Save Cartman0/152eacd23b793ecd3dbf5f706ae33e92 to your computer and use it in GitHub Desktop.
DiveIntoPython3 11章メモ(ファイル)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"toc": "true"
},
"cell_type": "markdown",
"source": "# Table of Contents\n <p><div class=\"lev1\"><a href=\"#11章-ファイル-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>11章 ファイル</a></div><div class=\"lev2\"><a href=\"#テキストファイルから読み込む-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>テキストファイルから読み込む</a></div><div class=\"lev3\"><a href=\"#文字コードが不快な姿を現す-1.1.1\"><span class=\"toc-item-num\">1.1.1&nbsp;&nbsp;</span>文字コードが不快な姿を現す</a></div><div class=\"lev3\"><a href=\"#ストリームオブジェクト-1.1.2\"><span class=\"toc-item-num\">1.1.2&nbsp;&nbsp;</span>ストリームオブジェクト</a></div><div class=\"lev3\"><a href=\"#テキストファイルからデータを読み込む-1.1.3\"><span class=\"toc-item-num\">1.1.3&nbsp;&nbsp;</span>テキストファイルからデータを読み込む</a></div><div class=\"lev3\"><a href=\"#ファイルを閉じる-1.1.4\"><span class=\"toc-item-num\">1.1.4&nbsp;&nbsp;</span>ファイルを閉じる</a></div><div class=\"lev3\"><a href=\"#ファイルを自動的に閉じる-1.1.5\"><span class=\"toc-item-num\">1.1.5&nbsp;&nbsp;</span>ファイルを自動的に閉じる</a></div><div class=\"lev3\"><a href=\"#データを一行ずつ読み込む-1.1.6\"><span class=\"toc-item-num\">1.1.6&nbsp;&nbsp;</span>データを一行ずつ読み込む</a></div><div class=\"lev2\"><a href=\"#テキストファイルに書き込む-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>テキストファイルに書き込む</a></div><div class=\"lev3\"><a href=\"#文字コード再び-1.2.1\"><span class=\"toc-item-num\">1.2.1&nbsp;&nbsp;</span>文字コード再び</a></div><div class=\"lev2\"><a href=\"#バイナリファイル-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>バイナリファイル</a></div><div class=\"lev2\"><a href=\"#ファイル以外をソースとするストリームオブジェクト-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>ファイル以外をソースとするストリームオブジェクト</a></div><div class=\"lev3\"><a href=\"#圧縮ファイルを扱う-1.4.1\"><span class=\"toc-item-num\">1.4.1&nbsp;&nbsp;</span>圧縮ファイルを扱う</a></div><div class=\"lev2\"><a href=\"#標準入力・標準出力・標準エラー出力-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>標準入力・標準出力・標準エラー出力</a></div><div class=\"lev3\"><a href=\"#標準出力をリダイレクトする-1.5.1\"><span class=\"toc-item-num\">1.5.1&nbsp;&nbsp;</span>標準出力をリダイレクトする</a></div><div class=\"lev2\"><a href=\"#参考リンク-1.6\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>参考リンク</a></div>"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Python3 1章メモ](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/d54093a99b9254c81bf1123adacbc48a/raw/eedc90bbbfc14e259854f2e739fffeec4cb4d8f7/DiveIntoPython3_01.ipynb)\n- [Dive Into Python3 2章メモ(ネイティブデータ型)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/988b51d8482ad9ade835bb07efdffb38/raw/784cf276b7cebe254e59f09dcea6f09eea760d38/DiveIntoPython3_02.ipynb)\n- [Dive Into Python3 3章メモ(内包表記)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/183ec6f6c835f621106f7c27d215290a/raw/bd7677946d6400bbe6acd257df7fb9c5976c3320/DiveIntoPython3_03.ipynb)\n- [Dive Into Python3 4章メモ(文字列)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/bb974f82e8a3fc74ac82c3c2a5b1a4f9/raw/63a80011c9391b451108c1a4dc804ec5ff125f34/DiveIntoPython3_04.ipynb)\n- [Dive Into Python3 5章メモ(正規表現)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/b834807a0dabb1c458b87be2f333a5ca/raw/37d6f25f67e017a569e1f0b60a9fcbe49d50515f/DiveIntoPython3_05.ipynb?flush_cache=true)\n- [Dive Into Python3 6章メモ(クロージャとジェネレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/a8998f8f88c5578271495ada56cc4809/raw/4e9b8ef3543016a710f905215693694acd703549/DiveIntoPython3_06.ipynb?flush_cache=true)\n- [Dive Into Python3 7章メモ(クラスとイテレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/8eb511c3b2aa6cadad6f6d49666c9db2/raw/60863d1ce1c1e9e4cb336ad79a0e252807beb87c/DiveIntoPython3_07.ipynb?flush_cache=true)\n- [Dive Into Python3 8章メモ(高度なイテレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/9ed3037cbdac59af53c20c125aed806e/raw/46ee3c71d72ab7ee665cf0c10f8717734632b462/DiveIntoPython3_08.ipynb?flush_cache=true)\n- [Dive Into Python3 9章メモ(ユニットテスト)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/1833320ab55ae5ea660ce0c635483d26/raw/46034833206366c8011594cbea2efce90168d54b/DiveIntoPython3_09.ipynb?flush_cache=true)\n- [Dive Into Python3 10章メモ(リファクタリング)](http://nbviewer.jupyter.org/gist/Cartman0/0c0af20eb95236da4da9547258fe2bb3?flush_cache=true)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "# 11章 ファイル"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## テキストファイルから読み込む"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルの内容を読み込む前に、まずはファイルを開かなければならない。:\n\n組み込み関数 `open()` が使える。\n```\na_file = open('examples/chinese.txt', encoding='utf-8')\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Pythonには組み込みの`open()`関数があり、\nこの関数は引数としてファイル名を受け取る。\nこの例でのファイル名は\n`'examples/chinese.txt'`。\nこのファイル名について、興味深いことが5つある:\n\n"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- これは単なるファイル名ではなく、\nディレクトリパスとファイル名の組み合わせになっている。\nファイルを開く関数としては、ディレクトリパスとファイル名の2つの引数をとるものも考えられるが、`open()`関数は1つだけ受け取る。\n一般にPythonで「ファイル名」が必要になる場面においては、\nその中にディレクトリのパスも含めることができる。\n\n- このディレクトリパスにはフォワードスラッシュが使われているが、\nWindowsではサブディレクトリを表すのにバックスラッシュを使う.\n一方で、Mac OS XやLinuxではフォワードスラッシュを使う。\nしかし、Pythonでは常に「フォワードスラッシュ `/`」を使えばいい。Windows上でもそれで動く。\n\n- このディレクトリパスはスラッシュやドライブレターから始まっていないので、\nこれは相対パスになる。\n\n- このファイル名は文字列だ。すべての現代的なオペレーティングシステム(Windowsも!)はファイル名やディレクトリ名を表すのにUnicodeを使っている。\nPython 3は非asciiのパス名を完全にサポートしている。\n\n- このファイルがローカルディスク上にある必要はない。\nコンピュータがファイルと見なし、\nファイルとしてアクセスできるものであれば、Pythonはそれを開くことができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 文字コードが不快な姿を現す"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "バイトはバイトであり、文字は抽象化。\n文字列はUnicode文字のシーケンス(並び)だが、\nディスク上のファイルはUnicode文字のシーケンスではなくバイトのシーケンスである。\n\nPythonは、特定の文字コードのエンコーディングアルゴリズムに従ってバイト列をデコードし、Unicode文字のシーケンス(つまり文字列)を返す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "file = open('examples/chinese.txt')\na_string = file.read()",
"execution_count": 1,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mUnicodeDecodeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-1-474ea7019c2e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0mfile\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'examples/chinese.txt'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma_string\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfile\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mUnicodeDecodeError\u001b[0m: 'cp932' codec can't decode byte 0x82 in position 19: illegal multibyte sequence"
],
"output_type": "error",
"ename": "UnicodeDecodeError",
"evalue": "'cp932' codec can't decode byte 0x82 in position 19: illegal multibyte sequence"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字コードを指定しなかったので、\nPythonはデフォルトの文字コードを使わった。\n\nデフォルトの文字コードとは、\nTracebackをよく見てみると、\nプログラムは `cp932.py` で停止している。\nこれは、ここでのデフォルトの文字コードとしてPythonがCP-932を使っていることを意味している。\nCP-932文字セットはこのファイルに含まれている文字をサポートしていないので、UnicodeDecodeErrorを伴って読み込みは失敗する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "デフォルトの文字コードはプラットフォームに依存するので、\nあなたのコンピュータではこのコードが問題なく動くかもしれないが(デフォルトの文字コードがutf-8の環境であればエラーは出ない)、\nこれを誰か他の人(CP-932などの異なるデフォルトの文字コードの環境の人)に配布したとたんに動かなくなってしまう。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### ストリームオブジェクト"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`open()`関数は、\n**ストリームオブジェクト** と呼ばれるものを返す。\nストリームオブジェクトは、文字のストリームから情報を取得したり、\n文字のストリームを操作するためのメソッドや属性を持っている。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": " a_file = open('examples/chinese.txt', encoding='utf-8')",
"execution_count": 2,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`name`属性は、\nファイルを開く際に`open()`関数に渡したパス名を表している。\nパスは、絶対パスへと正規化されてはいない。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.name",
"execution_count": 3,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'examples/chinese.txt'"
},
"metadata": {},
"execution_count": 3
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`encoding`属性は、`open()`関数に渡した文字コードを表している。\nファイルを開くときに文字コードを指定しなかった場合は、\n`locale.getpreferredencoding()` の戻り値が `encoding`属性の値になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.encoding",
"execution_count": 4,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'utf-8'"
},
"metadata": {},
"execution_count": 4
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import locale\nlocale.getpreferredencoding()",
"execution_count": 5,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'cp932'"
},
"metadata": {},
"execution_count": 5
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`mode`属性は、ファイルがどのモードで開かれたのかを教えてくれる。\n`open()`関数にはオプションとして `mode`パラメータを渡すことができる。\n\nファイルを開く際にモードを指定しなかったので、\nここではデフォルト値の`'r'`がパラメータの値になっている。\nこの'r'は、ファイルを読み込み専用のテキストモードで開くという意味だ。\nこの章で後ほど見るように、ファイルモードはいくつかの目的のために使われる。\nモードを使い分けることによって、ファイルに書き込んだり、\nファイルに追記したり、\nファイルをバイナリモード(ファイルを文字列ではなくバイト列として扱うモード)で開くことができる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "a_file.mode",
"execution_count": 6,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'r'"
},
"metadata": {},
"execution_count": 6
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### テキストファイルからデータを読み込む#"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルを読み込み用に開いたら、次は、そのファイルの中身を読み込む。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "いったん(正しい文字コードで)ファイルを開いてしまえば、\nそこからの読み込みはストリームオブジェクトの `read()`メソッドを呼び出すだけ。\n読み込みの結果として文字列が返される。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file = open('examples/chinese.txt', encoding='utf-8')\na_file.read() ",
"execution_count": 7,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'Dive Into Python あ\\n'"
},
"metadata": {},
"execution_count": 7
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "再びファイルの読み込みを行っても例外は発生しない。\nPythonは、ファイルの終端 (EOF) からさらに読み込もうとしてもエラーとは見なさず、\n単に空の文字列を返す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read()",
"execution_count": 8,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "''"
},
"metadata": {},
"execution_count": 8
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルを再び読み込みたいときはどうすればいいか"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`seek()`メソッドを使えば、ファイルの特定のバイト位置へ移動できる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.seek(0)",
"execution_count": 9,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "0"
},
"metadata": {},
"execution_count": 9
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`read()`メソッドは、オプション引数として、**読み込む文字数**を受け取ることができる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read(16)",
"execution_count": 10,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'Dive Into Python'"
},
"metadata": {},
"execution_count": 10
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "1文字ずつ読み込むこともできる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "a_file.read(1)",
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "' '"
},
"metadata": {},
"execution_count": 11
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "a_file.read(1)",
"execution_count": 12,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'あ'"
},
"metadata": {},
"execution_count": 12
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "今何バイト目にいるかは`tell`メソッドを使う。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": " a_file.tell()",
"execution_count": 13,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "20"
},
"metadata": {},
"execution_count": 13
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "17バイト目に移動"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.seek(17)",
"execution_count": 14,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "17"
},
"metadata": {},
"execution_count": 14
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "1文字読み込む。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read(1)",
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'あ'"
},
"metadata": {},
"execution_count": 15
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "現在、20番目のバイトにいる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.tell()",
"execution_count": 16,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "20"
},
"metadata": {},
"execution_count": 16
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- `seek()` と `tell()`メソッドは常に位置をバイト単位で数える。\n\nファイルをテキストとして開いたので、\n- `read()`メソッドは文字単位で数える。\n\n中国語・日本語の文字をutf-8 で表すには数バイトが必要になる。\nファイル中の英語の文字は1つの文字ごとに1バイトしか必要としないので、\n`seek()`と`read()`メソッドは同じものを数えていると勘違いしていまうかもしれない。\nだが、それは一部の文字にしか当てはまらない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "1. 18番目のバイトに移動し、1文字の読み込みを試みる。\n\n2. 理由は、18番目のバイトに文字がない。\n最も近くにある文字は17番目のバイトから始まっている(そして3バイト続いている)。\n中途半端な位置から文字を読み込もうとすると`UnicodeDecodeError` によって処理は失敗する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "a_file.seek(18)\na_file.read(1)",
"execution_count": 17,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mUnicodeDecodeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-17-33892425c5e3>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[0ma_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mseek\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m18\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32mC:\\Miniconda3\\lib\\codecs.py\u001b[0m in \u001b[0;36mdecode\u001b[1;34m(self, input, final)\u001b[0m\n\u001b[0;32m 319\u001b[0m \u001b[1;31m# decode input (taking the buffer into account)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 320\u001b[0m \u001b[0mdata\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mbuffer\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0minput\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 321\u001b[1;33m \u001b[1;33m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mconsumed\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_buffer_decode\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0merrors\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mfinal\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 322\u001b[0m \u001b[1;31m# keep undecoded input until the next call\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 323\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mbuffer\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mdata\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mconsumed\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mUnicodeDecodeError\u001b[0m: 'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte"
],
"output_type": "error",
"ename": "UnicodeDecodeError",
"evalue": "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### ファイルを閉じる"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルを開くとシステムリソースが消費されるし、\nファイルモードによっては他のプログラムがそのファイルにアクセスできなくなるかもしれない。ファイルを使い終えたら、すみやかにそのファイルを閉じることが重要だ。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "a_file.close()",
"execution_count": 18,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ストリームオブジェクトの `a_file` はまだ存在している。\nストリームオブジェクトの `close()`メソッドを呼び出しても、\nそのオブジェクト自体は破棄されない。\nしかし、このオブジェクトは何の役にも立たない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "閉じたファイルから読み込むことは出来ない。\nこれは `IOError`例外を送出する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read()",
"execution_count": 19,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-19-9419ea0432b8>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ma_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mValueError\u001b[0m: I/O operation on closed file."
],
"output_type": "error",
"ename": "ValueError",
"evalue": "I/O operation on closed file."
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "閉じたファイルをシークすることはできない。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": " a_file.seek(0)",
"execution_count": 20,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-20-21c0975b9185>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ma_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mseek\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mValueError\u001b[0m: I/O operation on closed file."
],
"output_type": "error",
"ename": "ValueError",
"evalue": "I/O operation on closed file."
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "閉じたファイルには現在位置が存在しないので、\n`tell()`メソッドも使えない。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.tell()",
"execution_count": 21,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-21-b50dc813ecb7>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ma_file\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtell\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mValueError\u001b[0m: I/O operation on closed file."
],
"output_type": "error",
"ename": "ValueError",
"evalue": "I/O operation on closed file."
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "既に閉じられたストリームオブジェクトの `close()` を呼び出しても、\n例外は発生しない。何も行われないだけ。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "a_file.close()",
"execution_count": 22,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "閉じたストリームオブジェクトには、1つだけ有用な属性がある。\nそれは `closed`属性で、これによってファイルが閉じられているかが確認できる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.closed",
"execution_count": 23,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "True"
},
"metadata": {},
"execution_count": 23
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### ファイルを自動的に閉じる"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ストリームオブジェクトには明白な `close()`メソッドがあるが、\nもしコードにバグがあり、`close()` を呼び出す前にクラッシュしてしまったら、\n理論的には、ファイルが必要以上に開かれ続けることになりうる。\nこれはローカルコンピュータでデバッグしている時点では大した問題にならないが、\n実運用するサーバ上ではおそらく問題となる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "解決策が Python 2.6 で導入されていて、\nPython 3 でも、その解決策`with`文が使える。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "以下のコードは `open()` を呼び出しているが、\n`a_file.close()` の呼び出しはどこにもない。\n\n`with`文は、コードブロックを開始する。\nこのコードブロックの中では、\n定めた変数 `a_file` を、`open()` から返されたストリームオブジェクトを表すものとして使うことができる。\n`seek()` や `read()` など、\n必要とするすべての標準のストリームオブジェクトメソッドが利用できる。\n`with`ブロックの終わりに達すると、\nPythonは `a_file.close()` を **自動的に呼び出す**。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/chinese.txt', encoding='utf-8') as a_file:\n a_file.seek(17)\n a_character = a_file.read(1)\n print(a_character)",
"execution_count": 24,
"outputs": [
{
"text": "あ\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "いつ・どのようにwithブロックを抜け出したとしても、\nPythonはそのファイルを閉じる。\n\nたとえば、未処理例外によって「抜け出した」ときでも閉じる。\nコードが例外を発生し、プログラム全体が悲鳴を上げて停止したとしても、\nそのファイルは閉じられる。これは保証されている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "技術的な用語で言えば、\n`with`文は「実行時コンテクスト」というものを生成する。\nこの例では、ストリームオブジェクトはコンテクストマネージャとして機能する。\nPython は a_fileというストリームオブジェクトを作り、\nそのオブジェクトに対して実行時コンテクストに入ることを告げる。\n`with`コードブロックが終了すると、\nPythonはストリームオブジェクトに対して、ランタイムコンテクストから抜け出すことを告げ、\nストリームオブジェクトは自身の `close()`メソッドを呼び出す。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`with`文はファイルのためだけの構文ではない。\nwith文は、実行時コンテクストを作成し、\nそのコンテクストへの入出をオブジェクトに伝える汎用のフレームワークにすぎない。\n\n対象となるオブジェクトがストリームオブジェクトなら、\nファイルライクな処理(例えばファイルを自動で閉じる)が行われる。\nだけれど、その振る舞いはwith文に定義されているのではなく、\nストリームオブジェクトの中で定義されている。\nコンテクストマネージャは、ファイルとは関係のない様々な用途で使用できる。\n独自のコンテクストマネージャを作ることもできる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### データを一行ずつ読み込む"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "テキストファイルの「行」というのは、いくつか単語を入力してENTERを押せば、\n新しい行に入る。テキストの行は文字のシーケンスであって、\nそれは改行文字によって区切られている.\n\nこの改行文字とは\n実のところ、これは複雑な問題で、現実には何種類もの文字が行の末尾を表す記号として使われている。\nこの問題については、どのOSも独自の慣習を持っている。\n行の終わりにキャリッジリターン文字を使うOSもあれば、\nラインフィード文字を使うOSもあるし、この二つをまとめて行末に置くOSもある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Pythonはデフォルトで行の末尾を自動的に処理してくれる。\n「ファイルを一行ずつ読みたい」と言えば、\nPythonはテキストファイルで使われている行終端の種類を自動で判別してくれるので、\n何の問題も起きない。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "もし行の終端として何を使うかを細かく制御する必要がある場合は、\n`open()`関数にオプションの `newline`パラメータを渡すことができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": " ファイルを1行ずつ読む方法"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "1.withパターンを使い、安全にファイルを開き、Pythonに閉じさせる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "2.ファイルを1行ずつ読み込むにはforループを使えばいい。\nストリームオブジェクトは `read()` のような明示的なメソッドを持つだけではなく、\nイテレータとしても振る舞う。\nこのイテレータは、値が要求されるたびに1つの行を返す。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "line_number = 0\nwith open('examples/favorite-people.txt', encoding='utf-8') as a_file: # 1\n for a_line in a_file: # 2\n line_number += 1\n print('{} {}'.format(line_number, a_line.rstrip()))\n \n",
"execution_count": 25,
"outputs": [
{
"text": "1 Dora\n2 Ethan\n3 Wesley\n4 John\n5 Anne\n6 Mike\n7 Chris\n8 Sarah\n9 Alex\n10 Lizzie\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "3.文字列の `format()`メソッドを使うことで、\n行番号と行自身を出力することができる。\n\nこのフォーマット指定子`{:>4}`は\n「4文字分のスペースに右詰めする」ことを意味する。\na_line変数は行全体を含んでおり、\nそれには改行文字も含まれる。\n\n文字列メソッドの `rstrip()` は、改行文字を含む行末の空白を取り除く。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "line_number = 0\nwith open('examples/favorite-people.txt', encoding='utf-8') as a_file: # 1\n for a_line in a_file: # 2\n line_number += 1\n print('{:>4} {}'.format(line_number, a_line.rstrip())) # 3\n \n",
"execution_count": 26,
"outputs": [
{
"text": " 1 Dora\n 2 Ethan\n 3 Wesley\n 4 John\n 5 Anne\n 6 Mike\n 7 Chris\n 8 Sarah\n 9 Alex\n 10 Lizzie\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## テキストファイルに書き込む"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルへの書き込みは、読み込みとほぼ同じ方法で行うことができる。\nまずファイルを開いてストリームオブジェクトを取得し、\n次にストリームオブジェクトのメソッドを使ってファイルにデータを書き込み、\n最後にファイルを閉じる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルを書き込み用に開くには、書き込みモードを指定して `open()`関数を呼びだす。\n書き込み用のファイルモードは2種類ある:\n\n- 「書き込み」モードはファイルを上書きする。`open()`関数に\n`mode='w'` を渡す。\n- 「追記」モードはファイルの終わりにデータを追加する。\n`open()`関数に `mode='a'` を渡す。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "どちらのモードであっても、ファイルがまだ存在していない場合にはファイルを自動的に作成するので、\n「初回でも開けるようにファイルがまだ存在しない場合には空のファイルを作成する関数」のような厄介なものは決して必要ない。ファイルを開いて書き始めるだけでいい。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "書き込みが終わったら、できるだけ速やかにファイルを閉じるようにする。\nそうすれば、書き込んだ内容がディスクに確実に保存されるし、\nファイルハンドルも解放される。ファイルを読み込むときと同じで、ストリームオブジェクトのclose()メソッドを使うこともできるし、with文を使ってPythonに閉じさせることもできる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "新しいファイル `test.log` を作成し(もしくは既存のファイルを上書きし)、\nそのファイルを書き込み用に開くことから始める。\n`mode='w'`パラメータはファイルを書き込み用に開くことを意味している。\nそう、これはとても危険なことだ。もしこのファイルが既に存在していたのなら、消えてしまう。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`open()`関数から返されたストリームオブジェクトの`write()`メソッドを使うことで、\n新しく開いたファイルにデータを追加することができる。\n`with`ブロックが終わると、Pythonは自動的にファイルを閉じる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "with open('test.log', mode='w', encoding='utf-8') as a_file:\n a_file.write('test succeeded') ",
"execution_count": 27,
"outputs": []
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "with open('test.log', encoding='utf-8') as a_file:\n print(a_file.read())",
"execution_count": 28,
"outputs": [
{
"text": "test succeeded\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "今度はファイルへ上書きするのではなく、\n`mode='a'` を用いてファイルに追記する。\n追記によってファイルの既存の内容が破壊されることは絶対に無い。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "with open('test.log', mode='a', encoding='utf-8') as a_file:\n a_file.write('and again')",
"execution_count": 29,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "書き込んだ元の行と、2回目に追加した行の両方が\n`test.log`ファイルに含まれている。\n改行(キャッリッジリターン・ラインフィード)が含まれていないことにも注意。\n改行文字をファイルに明示的に書き込まなかったので、ファイルはそれを含んでいない。\nキャリッジリターンは文字`'\\r'` として書き込むことができるし、\nラインフィードは文字`'\\n'` として書き込むことができる。\nこのどちらも行っていないので、ファイルに書き込んだものはすべて1行になってしまっている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('test.log', encoding='utf-8') as a_file:\n print(a_file.read())",
"execution_count": 30,
"outputs": [
{
"text": "test succeededand again\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 文字コード再び"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルを書き込み用に開く際に、\n`open()`関数に `encoding`パラメータを渡している。 \nこれは非常に重要なので、決して省略してはならない。\nこの章の始めで見たように、ファイルは文字列ではなくバイト列を含んでいる。バイトのストリームを読み込んで文字列に変換するのに使う文字コードを指定したからこそ、「文字列」を読み込むことができるのだ。\nテキストファイルに書き込む場合には、同じ問題が裏返しになって現れる。ファイルに文字を書き込むことはできない。文字は抽象化だからだ。\nファイルに書き込むためには、文字列をバイトのシーケンスに変換する方式を指定する必要がある。\n\n正しい変換を行わせる唯一の方法は、ファイルを書き込み用に開くときに、\n`encoding` パラメータを指定すること。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## バイナリファイル"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルというのテキストばかりではない。いくつかのファイルには画像もある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルをバイナリモードで開くのはシンプルだが、違いはわずか。\nテキストモードで開く場合との唯一の差は、\n`mode`パラメータに`'b'` という文字を含める。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ファイルをバイナリモードで開くことによって取得したストリームオブジェクトはテキストファイルの時と同じ属性の多くを含んでいる。\nその1つに `mode` があり、これはopen()関数に渡した `mode`パラメータを反映している。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as a_image:\n print(a_image.mode)",
"execution_count": 31,
"outputs": [
{
"text": "rb\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "バイナリストリームオブジェクトは、\nテキストストリームオブジェクトと同様に `name`属性も持っている。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as a_image:\n print(a_image.name)",
"execution_count": 32,
"outputs": [
{
"text": "examples/beauregard.jpg\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "ここに1つの違いがある。\nバイナリストリームオブジェクトには `encoding`属性がないのだ。\nこの理由はお分かりだと思う。今は文字列ではなくバイト列を読み書きしているのだから、\n変換を施す必要などない。\nバイナリファイルを読み込む時は、書き込まれた内容をそのまま取り出している。そこに変換処理が入り込む余地はない。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as a_image:\n print(a_image.encoding)",
"execution_count": 33,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-33-0dce65528268>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mwith\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'examples/beauregard.jpg'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mmode\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'rb'\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0ma_image\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma_image\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mencoding\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mAttributeError\u001b[0m: '_io.BufferedReader' object has no attribute 'encoding'"
],
"output_type": "error",
"ename": "AttributeError",
"evalue": "'_io.BufferedReader' object has no attribute 'encoding'"
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as an_image:\n print(an_image.tell())",
"execution_count": 34,
"outputs": [
{
"text": "0\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列ではなく、バイト列を読み込んでいる。\nファイルをバイナリモードで開いたので、\n`read()`メソッドは文字数ではなく読み込むバイト数を引数にとる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as an_image:\n data = an_image.read(3) \n print(data)",
"execution_count": 35,
"outputs": [
{
"text": "b'\\xff\\xd8\\xff'\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as an_image:\n data = an_image.read(3) \n print(type(data))",
"execution_count": 36,
"outputs": [
{
"text": "<class 'bytes'>\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これが意味するのは、\n`read()` に渡した数と `tell()`メソッドが返すインデックスとのあいだには予想外の不一致が決して起き得ないということ。\n`read()`メソッドはバイトを読み込み、`seek()`と`tell()`メソッドは読み込んだバイト数を追跡する。\nバイナリファイルの場合、これらは常に一致する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as an_image:\n data = an_image.read(3) \n print(an_image.tell())",
"execution_count": 37,
"outputs": [
{
"text": "3\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "with open('examples/beauregard.jpg', mode='rb') as an_image:\n data = an_image.read() \n print(len(data))",
"execution_count": 38,
"outputs": [
{
"text": "3150\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## ファイル以外をソースとするストリームオブジェクト"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "今、ライブラリを書いているとしよう。\nそして、そのライブラリの1つの関数はファイルからデータを読み込もうとしているとする。\nその関数は、「ファイル名を文字列として受け取り、そのファイルを読み込み用に開き、それを読み込み、関数を抜け出る前にそのファイルを閉じる」という単純な設計にもできるが、そうすべきではない。\n\nその代わりに、API は任意のストリームオブジェクトを受け取るようにすべき。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "最も単純な場合、\n`read()`メソッド(オプションとしてsizeパラメータを受け取り、文字列を戻り値として返す)を持っているオブジェクトなら何だってストリームオブジェクトだといえる。\n`size`パラメータなしで呼ばれた場合は、\n`read()`メソッドは入力ソースを読み込んで、そのすべてのデータを一つの値として返さなければならない。\n`size`パラメータと共に呼び出された場合は、\n入力データからその分を読み込んで返す。\n再度呼ばれときは、中断した場所を見つけ、その次のデータの固まりを返す。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これは実際のファイルを開いたときのストリームオブジェクトに非常によく似ている。\n違いは本物のファイルだとは限らないということだ。\n\n「読み込む」入力ソースは何でも良く、Webページや、メモリ上の文字列、他のプログラムの出力でも良い。\n関数がストリームオブジェクトを受け取り、\nそのオブジェクトの `read()`メソッドを呼び出す限り、ファイルとして振る舞ういかなる入力であっても、それらを扱うための専用のコードなしに扱うことができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`io`モジュールは, `StringIO`クラスを定義しており、\nこれを使うと、メモリ上の文字列をあたかもファイルであるかのように扱うことができる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "a_string = 'PapayaWhip is the new black.'\nimport io ",
"execution_count": 39,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列からストリームオブジェクトを作るには、\n「ファイル」のデータとして扱いたい文字列を渡して\n `io.StringIO()`クラスのインスタンスを作成すればよい。\n ストリームオブジェクトを手に入れたので、これを使ってストリームライクなあらゆる操作ができる。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "a_file = io.StringIO(a_string)",
"execution_count": 40,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`read()`メソッドは「ファイル」の中身を全て「読み出す」関数だが、\n`StringIO` の場合は単純に元の文字列が返される。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read()",
"execution_count": 41,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'PapayaWhip is the new black.'"
},
"metadata": {},
"execution_count": 41
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "本物のファイルと同様に、read()メソッドをもう一度呼び出すと空の文字列が返される。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read()",
"execution_count": 42,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "''"
},
"metadata": {},
"execution_count": 42
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "StringIOオブジェクトのseek()メソッドを使うことで、本物のファイルをシークする時のように、文字列の先頭に明示的にシークすることができる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.seek(0)",
"execution_count": 43,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "0"
},
"metadata": {},
"execution_count": 43
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`size`パラメータを `read()`メソッドに渡すことで、\n文字列を小分けにして読み込むこともできる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read(10) ",
"execution_count": 44,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'PapayaWhip'"
},
"metadata": {},
"execution_count": 44
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.tell()",
"execution_count": 45,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "10"
},
"metadata": {},
"execution_count": 45
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.seek(18)",
"execution_count": 46,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "18"
},
"metadata": {},
"execution_count": 46
}
]
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "a_file.read()",
"execution_count": 47,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'new black.'"
},
"metadata": {},
"execution_count": 47
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- `io.StringIO` を使うと、\n文字列をテキストファイルのように扱うことができる。\n- `io.BytesIO`クラスというものもあり、\nこれを使うとバイト配列をバイナリファイルとして扱うことができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 圧縮ファイルを扱う"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Python標準ライブラリには、圧縮ファイルの読み書きをサポートするモジュールが含まれている。圧縮方式には様々な種類があるが、Windows以外のシステムにおいて最も広く使われているのはgzipとbzip2だ(PKZIPアーカイブやGNU Tarアーカイブにも出会ったことがあるかもしれない。Pythonには、これらを扱うモジュールも含まれている)。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`gzip`モジュールを使うと、\ngzipで圧縮されたファイルを読み書きするためのストリームオブジェクトを作成できる。\nこのモジュールによって生成されるストリームオブジェクトは`read()`メソッド(読み込み用に開いた場合)や `write()`メソッド(書き込み用に開いた場合)をサポートしている。\n\nつまり、解凍したデータを格納するための一時ファイルを作るなどということはせずに、通常のファイルを扱うためにすでに学んだメソッドを使って、\ngzip圧縮されたファイルを直接読み書きすることができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "さらに、このモジュールは `with`文もサポートしているので、gzipで圧縮されたファイルを使い終わったときに、それをPythonに自動的に閉じさせることもできる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import gzip\ngzip",
"execution_count": 48,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "<module 'gzip' from 'C:\\\\Miniconda3\\\\lib\\\\gzip.py'>"
},
"metadata": {},
"execution_count": 48
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "gzipで圧縮されたファイルは常にバイナリモードで開かなければならない\n(引数modeに文字'b'が含まれることに注意)。"
},
{
"metadata": {
"collapsed": true,
"trusted": true
},
"cell_type": "code",
"source": "with gzip.open('out.log.gz', mode='wb') as z_file:\n z_file.write('A nine mile walk is no joke, especially in the rain.'.encode('utf-8'))\n",
"execution_count": 49,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このzipファイルは、79バイトになる。\nこれは実のところ元の文字列よりもサイズが大きくなってしまっている。\ngzipファイル形式は、ファイルのメタデータを保持する固定長のヘッダを持っているので、非常に小さいファイルに対しては非効率になる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true,
"scrolled": false
},
"cell_type": "code",
"source": "with gzip.open('out.log.gz', mode='rb') as z_file:\n print(len(z_file.read()))",
"execution_count": 50,
"outputs": [
{
"text": "52\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "このファイルを解凍してその内容を新しいファイルに保存する。\n保存されるファイルの名前は、圧縮ファイルの名前から拡張子の `.gz`を取り除いたものになる。\n\n```\nout.log\n```\nが生成される。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 標準入力・標準出力・標準エラー出力"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "標準出力と標準エラー出力(一般にstdout, stderrと略される)は、Mac OS XやLinuxのようなすべてのUNIXライクなシステムに標準で組み込まれているパイプだ。\n\n- print()関数を呼び出すと、印字しようとしたものは\n**`stdout`**パイプに送られる。\n- プログラムがクラッシュしてTracebackを印字しようとしたときは、\nそれが **`stderr`**パイプに送られる。\n\nデフォルトでは、作業している端末ウインドウに両方のパイプが接続されている。プログラムが何かを印字するときは、その結果を端末ウインドウで見ることになるし、プログラムがクラッシュするときは、同様にTracebackを端末ウインドウで見ることになる。\n\nグラフィカルなPythonシェルでは、stdoutとstderrパイプはデフォルトで「対話ウインドウ」に接続されている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "今までよく使っていたループの中のprint()関数。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "for i in range(3):\n print('PapayaWhip')",
"execution_count": 51,
"outputs": [
{
"text": "PapayaWhip\nPapayaWhip\nPapayaWhip\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`stdout`は `sys`モジュールで定義されている。\nそしてこれはストリームオブジェクトになる。\nこれの`write()`関数を呼び出すと、\nそこに与えた文字列をなんでも表示する。\n\n実際に、これが `print`関数の行っていること。\n`print`関数は表示する文字列の末尾に改行を追加して、\n`sys.stdout.write` を呼び出している。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import sys\nfor i in range(3):\n sys.stdout.write('is the')",
"execution_count": 52,
"outputs": [
{
"text": "is theis theis the",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "最も単純な場合では、\n`sys.stdout` と `sys.stderr` は同じ場所、\nつまりPython ide(その中にいる場合)、\nもしくは端末(Pythonをコマンドラインから実行している場合)に出力する。\n標準出力と同様に、標準エラー出力も改行を追加してくれない。\n改行したい場合は、改行文字を書き込む必要がある。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "for i in range(3):\n sys.stderr.write('new black')",
"execution_count": 53,
"outputs": [
{
"text": "new blacknew blacknew black",
"output_type": "stream",
"name": "stderr"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`sys.stdout` と `sys.stderr` はストリームオブジェクトだが、\nこれらは書き込み専用になる。\nこれらの `read()`メソッドを呼び出そうとすると、常に `IOError` が発生する。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import sys\nsys.stdout.read()",
"execution_count": 54,
"outputs": [
{
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mOSError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-54-b249ed7d8dd2>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0msys\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0msys\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstdout\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32mC:\\Miniconda3\\lib\\site-packages\\ipykernel\\iostream.py\u001b[0m in \u001b[0;36mread\u001b[1;34m(self, size)\u001b[0m\n\u001b[0;32m 298\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 299\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0msize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 300\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mIOError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'Read not supported on a write only stream.'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 301\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 302\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mreadline\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0msize\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mOSError\u001b[0m: Read not supported on a write only stream."
],
"output_type": "error",
"ename": "OSError",
"evalue": "Read not supported on a write only stream."
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 標準出力をリダイレクトする"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`sys.stdout` と `sys.stderr` は、\n書き込みのみをサポートするストリームオブジェクト。\nしかし、これらは定数ではなく「変数」だ。\nこれが意味するのは、新しい値、つまり任意のストリームオブジェクトを代入することで、\nこれらの出力先をリダイレクトできる。"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "import sys\n\nclass RedirectStdoutTo:\n def __init__(self, out_new):\n self.out_new = out_new\n\n def __enter__(self):\n self.out_old = sys.stdout\n sys.stdout = self.out_new\n\n def __exit__(self, *args):\n sys.stdout = self.out_old\n\nprint('A')\nwith open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file):\n print('B') # out.log へリダイレクトされる\nprint('C')",
"execution_count": 55,
"outputs": [
{
"text": "A\nC\n",
"output_type": "stream",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nprint('A')\nwith open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file):\n print('B')\nprint('C')\n```\n\nは書き換えると、\n\n```\nwith open('out.log', mode='w', encoding='utf-8') as a_file:\n with RedirectStdoutTo(a_file):\n print('B')\n```\n\n実際には2つのwith文からなりたっている。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "「外側」のwith文:\n\nここではout.log という名前のutf-8でエンコードされたテキストファイルを書き込み用に開き、そのストリームオブジェクトを `a_file` という名前の変数に代入している。しかし奇妙な点はまだある。\n\n`with RedirectStdoutTo(a_file)`:\n\n`with`文は必ずしも `as`句を必要としない。\n関数を呼び出して、その戻り値を無視するときのように、\nwithコンテクストを変数へ代入しない `with`文を作ることもできる。\nこの例では、`RedirectStdoutTo`コンテクストの副作用だけが必要。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "`RedirectStdoutTo`クラスは、\nカスタマイズされた**コンテクストマネージャ**。\n\nどんなクラスも2つの特殊メソッド、\n`__enter__()` と `__exit__()` を定義することでコンテクストマネージャになることができる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nclass RedirectStdoutTo:\n def __init__(self, out_new): # 1\n self.out_new = out_new\n\n def __enter__(self): # 2 \n self.out_old = sys.stdout\n sys.stdout = self.out_new\n\n def __exit__(self, *args): # 3\n sys.stdout = self.out_old\n```\n\n1. `__init__()`メソッドはインスタンスが生成された直後に呼び出される。\nここでは1つの引数として、このコンテクストが存在する間だけ標準入力として使いたいストリームオブジェクトを受け取る。\nこのメソッドはストリームオブジェクトが後で他のメソッドから使えるように、\nインスタンス変数に保存するだけ。\n\n2. `__enter__()`メソッドは特殊クラスメソッド。\nPythonは、コンテクストに入るとき(つまりwith文の初め)にこのメソッドを呼び出す。\nこのメソッドは、`sys.stdout` の現在の値を `self.out_old` に保存し、\n次に `self.out_new` を `sys.stdout` に代入することによって標準出力をリダイレクトする。\n\n3. `__exit__()`メソッドはもう1つの特殊クラスメソッド。\nPythonは、コンテクストから抜けるとき(つまりwith文の最後)にこのメソッドを呼び出す。\nこのメソッドは、保存しておいたself.out_oldの値をsys.stdoutに代入することによって標準出力を元の値に戻す。\n"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "まとめ"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nprint('A') # 1\nwith open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file): # 2\n print('B') # 3\nprint('C') \n```\n\n1. この出力はide 「対話ウインドウ」(もしくは、スクリプトがコマンドラインで実行されているときはコマンドライン)に印字される。\n\n2. ここで、with文はカンマで区切られたコンテクストのリストを受け取っている。カンマで区切られたリストは、ネストされたwithブロックのように振る舞う。リストの最初のコンテクストが「外側」のブロックになり、最後のコンテクストが「内側」のコンテクストになる。最初のコンテクストはファイルを開き、次のコンテクストは、初めのコンテクストで作られたストリームオブジェクトへ `sys.stdout`をリダイレクトする。\n\n3. このprint()関数は、with文によって作られたコンテクストと共に実行されるので、その出力は画面に印字されず、out.logファイルに書き込まれる。\n④\twithコードブロックが終了した。ここでPythonは、各々のコンテクストマネージャに対して、コンテクストから抜け出るときに行うべき処理を実行するように告げる。コンテクストマネージャは後入れ先出し (LIFO) のスタックを形成している。終了の際は、2番目のコンテクストマネージャがsys.stdoutを元の値に戻し、次に1番目のコンテクストマネージャがout.logファイルを閉じる。標準出力が元の値に戻ったので、print()関数を呼び出すと再び画面上に印字されるようになる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "リダイレクトしないとどうなるか"
},
{
"metadata": {
"collapsed": false,
"trusted": true
},
"cell_type": "code",
"source": "print('A')\nwith open('out.log', mode='w', encoding='utf-8') as a_file:\n print('B') # ファイルには何も書かれずファイル書き込み終了\nprint('C')",
"execution_count": 56,
"outputs": [
{
"output_type": "stream",
"text": "A\nB\nC\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nsys.stdout = a_file # ファイルに繋ぎ変えて\n\nsys.stdout = sys.__stdout__ # で元に戻す。\n```\n\n参考:[標準入出力をファイルにつなぎ換える](http://lightson.dip.jp/zope/ZWiki/169_e6_a8_99_e6_ba_96_e5_85_a5_e5_87_ba_e5_8a_9b_e3_82_92_e3_83_95_e3_82_a1_e3_82_a4_e3_83_ab_e3_81_ab_e3_81_a4_e3_81_aa_e3_81_8e_e6_8f_9b_e3_81_88_e3_82_8b)"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 参考リンク"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Python3 11章 ファイル](http://diveintopython3-ja.rdy.jp/files.html)\n- [組み込み関数 open python doc](http://docs.python.jp/3/library/functions.html#open)\n- [io — ストリームを扱うコアツール python doc](http://docs.python.jp/3/library/io.html)\n- [sys.stdout と sys.stderr python doc](http://docs.python.jp/3.5/library/sys.html#sys.stdout)\n- [コンテキストマネージャ型 python doc](http://docs.python.jp/3/library/stdtypes.html#typecontextmanager)\n- [標準入出力をファイルにつなぎ換える](http://lightson.dip.jp/zope/ZWiki/169_e6_a8_99_e6_ba_96_e5_85_a5_e5_87_ba_e5_8a_9b_e3_82_92_e3_83_95_e3_82_a1_e3_82_a4_e3_83_ab_e3_81_ab_e3_81_a4_e3_81_aa_e3_81_8e_e6_8f_9b_e3_81_88_e3_82_8b)"
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"language_info": {
"mimetype": "text/x-python",
"version": "3.5.1",
"name": "python",
"file_extension": ".py",
"pygments_lexer": "ipython3",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"nbconvert_exporter": "python"
},
"toc": {
"toc_number_sections": true,
"toc_cell": true,
"toc_window_display": false,
"toc_threshold": "6"
},
"gist": {
"id": "152eacd23b793ecd3dbf5f706ae33e92",
"data": {
"description": "DiveIntoPython3 11章メモ(ファイル)",
"public": true
}
},
"_draft": {
"nbviewer_url": "https://gist.github.com/152eacd23b793ecd3dbf5f706ae33e92"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment