4-2.外部ファイルからデータの入出力を行おう
Numpyの基礎を理解したところで次にファイルの入出力を勉強しましょう.Numpyは外部ファイルからのデータの入力/Numpy-ndarrayのファイル出力が非常に簡単です.
(1) csvファイルの入出力
コンパイル言語では,指定した配列を入出力するのは面倒が伴います.しかし,Numpyではたった一行でファイルの入出力が終了します.
コンパイル言語では,指定した配列を入出力するのは面倒が伴います.しかし,Numpyではたった一行でファイルの入出力が終了します.
np.loadtxt(fname,delimiter...)
指定したファイルからデータをndarrayに格納する
delimiterは区切りを意味します
指定したファイルからデータをndarrayに格納する
delimiterは区切りを意味します
np.savetxt(fname,X,delimiter...)
delimiterで区切られた対象の配列Xを fnameとして保存する.
fnameには拡張子.csv等を入れる.
csvの場合のdelimiterは通常 “,”カンマである.
delimiterで区切られた対象の配列Xを fnameとして保存する.
fnameには拡張子.csv等を入れる.
csvの場合のdelimiterは通常 “,”カンマである.
Numpy_loadtextの例
- Water_demand = np.loadtext(“water_dem.csv”,delimiter=”,”)
-
Numpy_savetextの例
- fname = “test.csv”
- A = np.full(500,(12))
- np.savetxt(fname, A, demiliter =”,”)
-
(2) txtファイルの入出力
時々ではありますが,テキストファイルを取り扱うケースがあります.例えば,シミュレーションの際にどのようなパラメータを使用したかを記録したいが,エクセル経由で開くと速度が遅いことが気になるなどの場合です.テキストファイルの読み込みとして,以下のような文章をPythonに入れてみましょう.Read_test.txtは実行するReading.pyファイルと同じ場所にしましょう.
時々ではありますが,テキストファイルを取り扱うケースがあります.例えば,シミュレーションの際にどのようなパラメータを使用したかを記録したいが,エクセル経由で開くと速度が遅いことが気になるなどの場合です.テキストファイルの読み込みとして,以下のような文章をPythonに入れてみましょう.Read_test.txtは実行するReading.pyファイルと同じ場所にしましょう.
[Read_test.txt]
Even though it has never been validated by objective testing, Probabilistic Seismic Hazard Analysis (PSHA) has been widely used for almost 50 years by governments and industry in applications with lives and property hanging in the balance, such as deciding safety criteria for nuclear power plants, making official national hazard maps, developing building code requirements, and determining earthquake insurance rates \n
PSHA rests on assumptions now known to conflict with earthquake physics; many damaging earthquakes, including the 1988 Spitak, Armenia, event and the 2011 Tohoku, Japan, event, have occurred in regions relatively rated low-risk by PSHA hazard maps. No extant method, including PSHA, produces reliable estimates of seismic hazard. \n
Earthquake hazard mitigation should be recognized to be inherently political, involving a tradeoff between uncertain costs and uncertain risks. \n
Earthquake scientists, engineers, and risk managers can make important contributions to the hard problem of allocating limited resources wisely, but government officials and stakeholders must take responsibility for the risks of accidents due to natural events that exceed the adopted safety criteria.
Even though it has never been validated by objective testing, Probabilistic Seismic Hazard Analysis (PSHA) has been widely used for almost 50 years by governments and industry in applications with lives and property hanging in the balance, such as deciding safety criteria for nuclear power plants, making official national hazard maps, developing building code requirements, and determining earthquake insurance rates \n
PSHA rests on assumptions now known to conflict with earthquake physics; many damaging earthquakes, including the 1988 Spitak, Armenia, event and the 2011 Tohoku, Japan, event, have occurred in regions relatively rated low-risk by PSHA hazard maps. No extant method, including PSHA, produces reliable estimates of seismic hazard. \n
Earthquake hazard mitigation should be recognized to be inherently political, involving a tradeoff between uncertain costs and uncertain risks. \n
Earthquake scientists, engineers, and risk managers can make important contributions to the hard problem of allocating limited resources wisely, but government officials and stakeholders must take responsibility for the risks of accidents due to natural events that exceed the adopted safety criteria.
Mulargia et al. Physics of the Earth and Planetary Interiors, Vol.264, pp.63-75. Mar.2017.
Read.py
- f = open(“ Read_test.txt”) #テキストファイルを開く
- data = f.read() #テキストファイル全体を読み込む
- f.close() #テキストファイルを閉じる
- print(data)
- lines = data. split('\n') #行ごとにテキストを分割する改行コード
- for no,line in enumerate(lines): #文章毎に番号と文章の塊を出力する
- print(no,line)
-
Even though it has never been validated by objective testing, Probabilistic Seismic Hazard Analysis (PSHA) has been widely used for almost 50 years by governments and industry in applications with lives and property hanging in the balance, such as deciding safety criteria for nuclear power plants, making official national hazard maps, developing building code requirements, and determining earthquake insurance rates \n
PSHA rests on assumptions now known to conflict with earthquake physics; many damaging earthquakes, including the 1988 Spitak, Armenia, event and the 2011 Tohoku, Japan, event, have occurred in regions relatively rated low-risk by PSHA hazard maps. No extant method, including PSHA, produces reliable estimates of seismic hazard. \n
Earthquake hazard mitigation should be recognized to be inherently political, involving a …
Earthquake hazard mitigation should be recognized to be inherently political, involving a …
0 Even though it has never been validated by objective testing, Probabilistic Seismic Hazard Analysis (PSHA) has been widely used for almost 50 years by governments and industry in applications with lives and property hanging in the balance, such as deciding safety criteria for nuclear power plants, making official national hazard maps, developing building code requirements, and determining earthquake insurance rates \n
1 PSHA rests on assumptions now known to conflict with earthquake physics; many damaging earthquakes, including the 1988 Spitak, Armenia, event and the 2011 Tohoku, Japan, event, have occurred in regions relatively rated low-risk by PSHA hazard maps. No extant method, including PSHA, produces reliable estimates of seismic hazard. \n
2 Earthquake hazard mitigation should be recognized to be inherently political, involving a tradeoff between uncertain costs and uncertain risks. \n…
テキストファイルからのデータ取り込みはそんなに難しくはないと思います.ここで注意しなくてはならないのはf.close()です.これを忘れるとメモリーリークの原因となり,フリーズなどを引き起こします.5行目のdata. split('\n')は改行を示す('\n')を参照して文章データを分割するものです.今回の例では,文中に('\n')が3つ存在するので文章は4セクションに分けられました.enumerate(lines)を用いたforループはそれを確認しています.data.split('\n')を使わずにセクションに分けられた文章ファイルを取り込むにはreadlines()があります.
Readlines.py
- f = open(“ Read_test.txt”)
- data = f.readlines()
- f.close()
- for no,line in enumerate(data):
- print(no,line)
-
先程はclose()を忘れないように注意しましたが,pythonではwithブロックを使うとテキストの処理が終了すると当時に自動でcloseを行うように設定できます.私は安全性の観点からwithメソッドを多用しています.with以下の動作をネストにすることでネストを抜けたらcloseを自動で実行できるようになっています.”r”というのは読み込みを意味しています.同様に”w”は書き込み(write)を意味します.
with_read.py
- with open(“ Read_test.txt”, “r”) as f:
- data = f.readlines()
- for no,line in enumerate(data):
- print(no,line)
-
0 Even though it has never been validated by objective testing, Probabilistic Seismic…
with_write.py
- with open(“ Read_tst.txt”, “w”) as f:
- f.write(“aiueo 800”)
- f.write(“JSCE”)
-
※with_write.pyと同じパスにRead_tst.txtが生成され,writeした文字列がtxt内に記録されている.