初心者のためのpython入門

自分がつまづいたところやつまづきやすいところを中心に書いていきます。また、役に立つライブラリの紹介などをしていきます。

ファイルの操作[2]

前書き

今回は、テキストファイルから文字列の読み込みの説明をします。

read()によるテキストファイルの読み出し

read()は1度にファイルの全体を読み出すことができます。サンプルを見ましょう。

# read.py
f = open('theZenOfPython', 'rt') # 前回作成したファイルを開く
the_zen_of_python = f.read() # 読み出す
f.close() # ファイルを閉じる

print(len(the_zen_of_python)) 
# 実行結果 
857

ファイルの読み出しができていることがわかると思います。
read()には、引数に読み出したいデータ量を与えることができす。

# read.py
f = open('theZenOfPython', 'rt')
the_zen_of_python = f.read(100)
f.close()

print(len(the_zen_of_python))
# 実行結果
100
readline()によるテキストファイルの読み出し

readline()はファイルを1行ずつ読み出すことができます。サンプルを見ましょう。

f = open('theZenOfPython', 'rt')
the_zen_of_python = f.readline()
f.close()

print(len(the_zen_of_python))
print(the_zen_of_python, end="")
# 実行結果
33
The Zen of Python, by Tim Peters

実行結果は上記のようになり、1行目が読み出されていることがわかります。

readlines()によるテキストファイルの読み出し

readlines()は1度に1行ずつ読み出して、それらをリストとして保存します。サンプルを見ましょう。

f = open('theZenOfPython', 'rt')
the_zen_of_python = f.readlines()
f.close()

print(len(the_zen_of_python))
print(the_zen_of_python, end="")
# 実行結果
21
['The Zen of Python, by Tim Peters\n', '\n', 'Beautiful is better than ugly.\n', 'Explicit is better than implicit.\n', 'Simple is better than complex.\n', 'Complex is better than complicated.\n', 'Flat is better than nested.\n', 'Sparse is better than dense.\n', 'Readability counts.\n', "Special cases aren't special enough to break the rules.\n", 'Although practicality beats purity.\n', 'Errors should never pass silently.\n', 'Unless explicitly silenced.\n', 'In the face of ambiguity, refuse the temptation to guess.\n', 'There should be one-- and preferably only one --obvious way to do it.\n', "Although that way may not be obvious at first unless you're Dutch.\n", 'Now is better than never.\n', 'Although never is often better than *right* now.\n', "If the implementation is hard to explain, it's a bad idea.\n", 'If the implementation is easy to explain, it may be a good idea.\n', "Namespaces are one honking great idea -- let's do more of those!"]

実行結果は上記のようになります。結果からわかるように、読み出した行をリストに追加しています。
readlines()はreadline()を次のように実行したものと同値となります。

f = open('theZenOfPython', 'rt')
the_zen_of_python = []
for line in f: # ファイルから1行ずつ読み出す
    the_zen_of_python.append(line) # リストに追加する
f.close()

print(len(the_zen_of_python))
# 実行結果
21
後書き

お疲れ様でした。簡単にですがテキストファイルの取り扱いを説明しました。その他のファイルの取り扱い方法は各自調べてみてください。