プログラミング勉強の備忘録

主にpythonやスマホアプリを作るためのプログラミングで勉強した内容を忘れないように記載していきます。

【Python】open()のmodeについて

【はじめに】

今回はPythonの「open()」の引数「mode」についてのメモです。
「mode」の種類や使い方について、残しています。

<実施環境>

【コードと説明】

<一覧>

mode= 説明
r 読み込み
w 書き込み(新規作成)
a 追加書き込み
r+ 既存ファイルの読み書き
w+ ファイルの読み書き(新規作成)
a+ 追記・読み書き
t テキストモード
b バイナリモード

<共通>

今回は下記の内容の書かれた「text.txt」を使用していきます。

# text.txt
aaa
bbb
ccc

<読み込み>

# r
with open('./test.txt', mode='r') as f:
    s = f.read()
print(s)
# => aaa
#    bbb
#    ccc

「r」は読み取り専用の引数です。
ファイルがある場合のみ読み込むことができ、ファイルがない場合はエラーになります。

# ファイルがない場合
with open('./test.txt', mode='r') as f:
    s = f.read()
print(s)
# => Traceback (most recent call last):
#    File "D:/Python/EditDocumentProject/test.py", line 1, in <module>
#      with open('./test.txt', mode='r') as f:
#    FileNotFoundError: [Errno 2] No such file or directory: './test.txt'
# 書き込み処理を行なった場合
with open('./test.txt', mode='r') as f:
    f.write('ddd')
print(s)
# => Traceback (most recent call last):
#    File "D:/Python/EditDocumentProject/test.py", line 2, in <module>
#       with open('./test.txt', mode='r') as f:
#    FileNotFoundError: [Errno 2] No such file or directory: './test.txt'

<書き込み(新規作成)>

# w
with open('./test.txt', mode='w') as f:
    f.write('ddd')
# 書き込み後の「test.txt」
ddd

「w」は書き込み専用の引数です。ファイルが存在しない場合は作成します。
ファイルが存在する場合、内容が上書きされます。
そのため、書き込み処理というよりは、新しいファイルを作り直すイメージです。

# 読み込みを行なった場合
with open('./test.txt', mode='w') as f:
    s = f.read()
# => Traceback (most recent call last):
#    File "D:/Python/EditDocumentProject/test.py", line 2, in <module>
#       s = f.read()
#    io.UnsupportedOperation: not readable

<追加書き込み>

# a
with open('./test.txt', mode='a') as f:
    f.write('\nddd')
# 書き込み後の「test.txt」
aaa
bbb
ccc
ddd

「a」は追記する場合の引数です。
上記を見ると、「ddd」が追加されているのがわかります。
ファイルが存在しない場合は、新規作成します。
また、書き込み専用のため、読み込みを行なうとエラーになります。

# ファイルが存在しない場合
with open('./test.txt', mode='a') as f:
    f.write('ddd')
# 作成された「test.txt」
ddd
# 読み込みを行なった場合
with open('./test.txt', mode='a') as f:
    s = f.read()
# => Traceback (most recent call last):
#    File "D:/Python/EditDocumentProject/test.py", line 3, in <module>
#       s = f.read()
#    io.UnsupportedOperation: not readable

<既存ファイルの読み書き>

# r+
# 読み込み
with open('./test.txt', mode='r+') as f:
    s = f.read()
print(s)
# => aaa
#    bbb
#    ccc

「r+」は読み書きのできる引数です。
書き込み時は「w」の時のようにファイルそのものが変わるわけではなく、上書きになります。(頭の文字から書き変わっていく)

# 書き込み
with open('./test.txt', mode='r+') as f:
    f.write('ddd')
# 書き込み後の「test.txt」
ddd
bbb
ccc

頭の「aaa」が「ddd」に書き換わっています。

# ファイルがない場合
with open('./test.txt', mode='r+') as f:
    s = f.read()
# => Traceback (most recent call last):
#    File "D:/Python/EditDocumentProject/test.py", line 2, in <module>
#       with open('./test.txt', mode='r+') as f:
#    FileNotFoundError: [Errno 2] No such file or directory: './test.txt'

<ファイルの読み書き(新規作成)>

# w+
with open('./test.txt', mode='w+') as f:
    f.write('ddd')
# 書き込み後の「test.txt」
ddd

「w+」は「r+」と同じファイルの読み書きができる引数です。
しかし、「w+」は「w」と同様に新規ファイルの作成の様になっており、ファイルを開いた時点で中身は空の状態になっています。

with open('./test.txt', mode='w+') as f:
    s = f.read()
print(s)
# =>

上記の様に読み込みを行なうと、エラーにはなりませんが、中身は空になっています。(読み込みの使い道があるのか不明。)

<追記・読み書き>

# a+
with open('./test.txt', mode='a+') as f:
    f.write('\nddd')
# 書き込み後の「test.txt」
aaa
bbb
ccc
ddd

「a+」も基本的に「a」の動作に加えて読み込みもできる引数です。
しかし、読み込みを行なっても内容は空であり、「w+」同様にいまいち使い方がわかりませんでした。

with open('./test.txt', mode='a+') as f:
    s = f.read()
print(s)
# =>

<テキストモードとバイナリモード>

# t
with open('./test.txt', mode='rt') as f:
    s = f.read()
print(s)
# => aaa
# bbb
# ccc
# b
with open('./test.txt', mode='rb') as f:
    s = f.read()
print(s)
# => b'aaa\r\nbbb\r\nccc'

「t」はテキストモード、「b」はバイナリモードになります。
「rt」や「wb」の様にして使います。
正直、現状ではあまり気にしなくて良さそうなのでここでは詳しい内容は調べないでおきます。
こちらのサイトにバイナリモードについての記載がありました。

【後書き】

今回は「open()」の引数「mode」についてメモしました。
本来は「encoding」についても記載しようと思っていましたが、奥が深く残すだけの知識には足りないと思ったため、やめました。

【参考サイト】

今回の作業にあたり、下記サイトを参考にさせて頂きました。
sites.google.com
www.sejuku.net
note.mu
www.not-enough.org