PythonのTopに戻る
モードを指定してファイルを開く
まず、ファイルを開くには2つの方法がある。例えば sample.txt という名前のファイルを開くコードは以下のようになる。
# 方法①
f = open("sample.txt")
print(type(f))
# <class '_io.TextIOWrapper'>
f.close()
# 方法②
with open("sample.txt") as f:
print(type(f))
# <class '_io.TextIOWrapper'>
ファイルの開閉
方法①では open()
でファイルオブジェクトを作成し、close()
で閉じている。close()
を付けるのが煩わしければ方法②のように with
ブロックを使う方法もある。
ファイルを開くときに以下のモードを指定して開くことができる。
-
- r:読み取りモード
- w:書き込みモード
- a:追記モード
- x:新規作成モード
このように指定することでファイルの中身を誤って消してしまったり、上書きしてしまったりする悲しい事故を減らすことができる。
ファイルに書き込む
sample.txt という名前のファイルに十二支の名前を書き込むプログラムは以下のように書ける。
Zodiac = ["mouse", "ox", "tiger", "rabbit", "dragon", "snake", "horse", "sheep", "monkey", "cock", "dog", "boar"]
fname = "sample.txt"
with open(fname, mode="w") as file:
for s in Zodiac:
file.write(s+"\n")
ファイルに書き込む
ファイルは「書き込みモード」として開いている。書き込みにはwrite
メソッド、もしくはリストを書き込むwritelines()
メソッドを使う。いずれも自動では改行されないことに注意。
ファイルの中身を読み込む
以下のデータセットはとある試験の結果である。
score people %
895~ 2053 96.2
845~ 2626 91.3
795~ 3626 84.5
745~ 4388 76.3
695~ 4941 67.1
645~ 5356 57.1
595~ 5662 46.5
545~ 5640 35.9
495~ 5002 26.6
445~ 4476 18.2
395~ 3681 11.4
345~ 2841 6.1
295~ 1833 2.6
245~ 963 0.8
195~ 365 0.2
145~ 68 0
95~ 11 0
45~ 3 0
10~ 4 0
sample_data.txt
このファイルを読み込むには次のようにする。
fname = "sample_data.txt"
f = open(fname,"r")
for line in f.readlines():
choped_line = line[:-1]
print(choped_line)
f.close()
ファイルの読み込み①
f.readlines()
でファイル全体をリストとして読み込む。1行ずつ読み込みたい場合はf.readline()
を用いる(←単数形であることに注意!)。line[:-1]
としているのは末尾の改行を取り除くためである。
1行ずつ読み込むには以下のようにする。
fname = "sample_data.txt"
with open(fname) as f:
while True:
line = f.readline()
if line == '' :
break
print(line[:-1])
ファイルを1行ずつ読み込む
f.readline()
メソッドで読み込んだ時に最終行まで辿り着くと空文字列''
が返される。最終行かどうかのif
文の条件はif not line:
としても判定可能。
以下のようにwith
ブロックを使う方法も考えられる。
fname = "sample_data.txt"
with open(fname, mode="w") as f:
for line in f.readlines():
choped_line = line[:-1]
print(choped_line)
ファイルの読み込み②
また、for
ブロックで以下のようにまとめて書くこともできる。
fname = "sample_data.txt"
for line in open(fname,"r").readlines():
choped_line = line[:-1]
print(choped_line)
ファイルの読み込み③
open
の引数にファイルのパスを直接渡すようにすれば3行に収まる。
PythonのTopに戻る