Skip to content

Instantly share code, notes, and snippets.

@miyamoto-yuichiro
Last active April 23, 2019 06:42
Show Gist options
  • Save miyamoto-yuichiro/c7380ecb4e7159ee8da7d4f050f437d5 to your computer and use it in GitHub Desktop.
Save miyamoto-yuichiro/c7380ecb4e7159ee8da7d4f050f437d5 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# ファイル入出力"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"大量のデータを処理する場合には,ファイル入出力は欠かせない.\n",
"まず,ファイルへの文字列の書き込みを説明する."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ファイルへの書き込み"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonでファイルへ書き込む手続きは,大きく分けて\n",
"\n",
"* ファイルを開く,\n",
"* ファイルに書き込む,\n",
"* ファイルを閉じる,\n",
"\n",
"の3段階に別れる.\n",
"\n",
"まず,ファイルを開くには組込み関数openを使う."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file = open('test.txt', 'w')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"組込み関数openの第1引数は,開くファイルのファイル名である.\n",
"ファイル名は文字列で指定する.\n",
"この例ではtest.txtという名前のファイルを開いている.\n",
"\n",
"組込み関数openの第2引数は「どう開くか」の指定である.\n",
"\n",
"* 'w'ならばファイルに書き込むつもりでファイルを開く.\n",
"* 'r'ならばファイルを読み込むつもりでファイルを開く.\n",
"\n",
"この例では,test.txtというファイルに書き込むつもりで開いている.\n",
"指定された名前のファイルが存在しないならば,ファイルを開く瞬間に新たにファイルが生成される.\n",
"\n",
"組込み関数openの戻り値はファイルオブジェクトである.\n",
"ファイルオブジェクトは,大雑把に言えば,ファイルとプログラムをつなぐパイプみたいなものである.\n",
"パイプの中をデータが流れるとイメージして欲しい.\n",
"\n",
"次に,ファイルオブジェクトのメソッドwriteを使って,ファイルに書き込んでみる."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_file.write('Hello!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ファイルオブジェクトのメソッドwriteは,ファイルに文字列を書き込む.\n",
"より正確には,そのファイルオブジェクトに文字列を送る.\n",
"\n",
"メソッドwriteの引数は文字列である.\n",
"この例ではHello!という文字列を送って(書き込んで)いる.\n",
"\n",
"メソッドwriteの戻り値は,送られた(書き込まれた)文字数である.\n",
"この戻り値を使う場面は,あまりないかもしれない.\n",
"\n",
"なお,メソッドwriteを使っても,すぐにファイルに書き込まれるとは限らない.\n",
"処理速度の向上のため,多くのプログラミング言語では「書き込む文字数がある程度多く溜まったら,まとめて書き込む」という方針を取っている.\n",
"Pythonもその方針を取っている.\n",
"\n",
"確実にファイルに書き込ませるには,ファイルオブジェクトのメソッドflushを使う."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file.flush()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ファイルオブジェクトのメソッドflushは,それまでにファイルオブジェクトに溜められている文字を強制的にファイルに書き込む命令である.\n",
"\n",
"イメージ的には,パイプの中に溜まっているものを押し出すと思ってよい.\n",
"\n",
"ファイルに書き込みたい文字列を全てファイルオブジェクトに送ったら,最後にメソッドcloseでファイルオブジェクトを閉じる."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ファイルオブジェクトのメソッドcloseはファイルを閉じる.\n",
"\n",
"これでファイルへの文字列の書き込みは完了である.\n",
"なお,メソッドcloseの直前には必ずflushが行われるので,実はこの例ではflushは必要なかった.\n",
"\n",
"メソッドcloseを使わなくても上手くいく場合も多い.\n",
"しかし,確実ではないので,必ずcloseを使うことを習慣として欲しい.\n",
"\n",
"実際に文字列Hello!が書き込まれたファイルtest.txtを確認してみよう."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ファイルからの読み込み"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonでファイルから読み込む手続きも,書き込む場合と同様で,大きく分けて\n",
"\n",
"* ファイルを開く,\n",
"* ファイルから読み込む,\n",
"* ファイルを閉じる,\n",
"の3段階に別れる.\n",
"\n",
"やはり,ファイルを開くには組込み関数openを使う."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file = open('test.txt', 'r')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"書き込む場合と同様なので,説明は省略する.\n",
"\n",
"なお,組込み関数openの第2引数は省略可能で,省略すると'r'(すなわち読み込み)と見なされる.\n",
"言い換えると,組込み関数openの第2引数のデフォルト値は'r'である."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file = open('test.txt') # これでもtest.txtが「読み込みモードで」開かれる."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ファイルから文字列を読み込むメソッドはいろいろあるが,ここでは1行読み込むメソッドreadlineを使う"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"read_str = test_file.readline()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ファイルオブジェクトのメソッドreadlineの戻り値は,読み込まれた文字列である.\n",
"\n",
"この例では,読み込まれた文字列が変数read_strに代入される."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Hello!'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"read_str"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"read_strの中身を確認すると,確かに文字列が読み込まれている.\n",
"\n",
"ファイルから読み込みたい文字列をすべて読みこんだら,最後にメソッドcloseでファイルオブジェクトを閉じる."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"これでファイルからの文字列の読み込みは完了である.\n",
"\n",
"ファイルからの読み込みの場合には,ファイルに書かれている文字列の全てを読み込む必要は必ずしもない.\n",
"途中でやめても問題ない.\n",
"\n",
"また,ファイルからの読み込みの場合には,closeメソッドを使わなくても不具合は生じにくい.\n",
"しかし,自分で書いたコードの可読性の維持のためにも,「お行儀よく」必ずcloseを使うことを習慣として欲しい."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ファイルを閉じても,読み込んだ情報が消えるわけではない.\n",
"\n",
"この例では,read_strに代入された値はそのままである."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello!\n"
]
}
],
"source": [
"print(read_str)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 複数行の文字列のファイル入出力"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ここまでは1行の文字列をファイルに書き込んだり,ファイルから読み込んだりするだけであった.\n",
"これだけでは複数行の文字列のファイルへの書き込み,ファイルからの読み込みはわからないかもしれない.\n",
"次に複数行の文字列を扱う.\n",
"\n",
"以下に,2つのファイルtest2.txtとtest3.txtに複数行の文字列を書き込む例を挙げる."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"test_file = open('test2.txt', 'w')\n",
"test_file.write('Hello!\\nPython')\n",
"test_file.flush() # 直後にcloseがあるので,この命令はなくても良い.\n",
"test_file.close()\n",
"test_file = open('test3.txt', 'w')\n",
"test_file.write('Hello!\\nPython\\n')\n",
"test_file.flush() # こちらも直後にcloseがあるので,この命令はなくても良い.\n",
"test_file.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"'\\n'は改行を表す特殊な文字である.\\nで1文字という扱いである.改行文字とよばれる.\n",
"\n",
"この例では,test2.txtというファイルに'Hello!'という行と'Python'という行が書き込まれる.\n",
"つまり,複数行の文字列は,改行文字で区切られた「1つの文字列」である.\n",
"\n",
"test3.txtにも'Hello!'という行と'Python'という行が書き込まれる.\n",
"test2.txtとの違いは「最後にも改行文字が入っている」というところだけである.\n",
"\n",
"test2.txtとtest3.txtの2つのファイルをテキストエディターで見て,その内容を確認してみよう."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に,2行の文字列が書かれているファイルtest2.txtの文字列を読み込んでみる.\n",
"複数行の文字列を読む方法はいくつかあるが,まずはファイルオブジェクトのreadlinesというメソッドを使ってみる."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Hello!\\n', 'Python']\n"
]
}
],
"source": [
"test_file = open('test2.txt', 'r') # この場合は第2引数を省略しても良い.\n",
"lines = test_file.readlines()\n",
"test_file.close()\n",
"print(lines)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"この例でわかるように,複数行の文字列が書かれているファイル(のファイルオブジェクト)でreadlinesを使うと,各行が要素となった文字列が得られる.\n",
"あとは,リストに対する操作を駆使して,好きに文字列をいじってほしい.\n",
"\n",
"なお,改行文字は入ったままなので,場合によっては注意が必要である.\n",
"\n",
"念のため,上記リストlineの中身をそれぞれ確認してみる."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Hello!\\n'"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lines[0]"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Python'"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lines[1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"改行文字が入ったままだと,いろいろ扱いづらい場合も多い.\n",
"よって,改行文字などを取り除くメソッドも用意されている."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Hello!'"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lines[0].rstrip()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Python'"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lines[1].rstrip()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"文字列のメソッドrstrip()は文字列の最後の空白文字(スペース,改行文字,タブ文字など)をすべて除いた文字列を返すメソッドである.\n",
"\n",
"この例でわかるように,もともと最後に空白文字がないならば何もしない.\n",
"\n",
"rstripの類似品にlstripがある.\n",
"lstripは文字列の最初の空白文字をすべて除いた文字列を返すメソッドである.\n",
"また,rstripとlstripの両方の仕事を一度にやってくれるstripというメソッドもある.\n",
"\n",
"他にも同様に有用なメソッドはいろいろある.\n",
"必要に応じて「Python 文字列 メソッド」で検索すると良い."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment