初心者のためのpython入門

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

ファイルの操作[1]

前書き

今回からファイルの操作について説明します。

ファイルを開く

ファイルを開くにはopen関数を仕様します。サンプルを見ましょう。open()の使い方は以下のようになります。

fileobj = open(filename, mode)

  • fileobj : open()が返すファイルオブジェクトです。
  • filename : 開きたいファイル名(文字列)を指定します。
  • mode : ファイルのタイプやファイルをどのように操作するかを知らせる文字列を指定します。

modeを指定する文字列

  • ファイルの操作
記号 意味
r 読み出し
w 書き込み(ファイルが存在しない場合、新しいファイルを作成、存在する場合は上書き)
x 書き込み(ファイルが存在する場合はエラーとなる)
a 追記
  • ファイルの種類
記号 意味
t(またはなし) テキストファイル
b バイナリファイル

指定例
以下に使用例をあげておきます。

fileobj = open('sample.txt', 'wt') # テキストで開き、書き込み 
fileobj = open('sample.txt', 'a')  # テキストで開き、追記
fileobj = open('sample.txt', 'rb') # バイナリで開き、読み出し
write()による書き込み

テキストファイルに書き込むにはwrite()を使います。サンプルを見ましょう。

#write.py
the_zen_of_python = '''The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

f = open('theZenOfPython', 'wt') # ファイルを開く
f.write(the_zen_of_python) # ファイルに書き込む
f.close() # ファイルを閉じる

上記のコードを実行すると、実行ファイル(write.py)と同じディレクトリにファイル(theZenOfPython)が作成されます。また、ファイルを開き処理が終わったら、必ず最後にclose()で閉じましょう。

print()による書き込み

先ほどの例ではwrite()を使いましたが、print()でも書き込むことができます。

# print.py
the_zen_of_python = ''' ... ''' # 先程と同じ文字列

f = open('theZenOfPython', 'wt') # ファイル開く
print(the_zen_of_python, file=f) # print()の出力先にfを指定する
f.close() # ファイルを閉じる

上記のコードを実行すると、先程と同じようになります。print()は出力先を指定することができ、そこにファイル(f)を指定するとファイルに書き込めます。

write()とprint()の違い

デフォルトのprint()は、ここの引数の後にスペースを追加し、全体の末尾に改行を追加します。そのため、write()とprint()に違いが生じます。print()をwrite()と同じように仕様するためには、sep引数とend引数を指定してあげる必要があります。

print()の引数

引数 意味
sep セパレータ。デフォルトではスペース(' ')。
end 末尾の文字列。デフォルトでは改行('\n')。
file 出力先。デフォルトでは標準出力(stdout)。
後書き

今回はファイルの開き方とファイルへの書き込みを説明しました。次回は、ファイルからの読み出しを説明します。