Python ファイルの読み書き #1
株式会社リュディアです。今回からファイルの読み書きについてまとめていきます。
まずファイルの読み込みからまとめていきます。読み込むファイルは英語版 Wikipedia の Python についての説明の冒頭の 2センテンスを使います。またピリオド毎に改行を追加したました。このファイルを text_test.txt という名前で保存して例文として使います。
Python is an interpreted high-level general-purpose programming language.
Python's design philosophy emphasizes code readability with its notable use of significant indentation.
Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
Python is dynamically-typed and garbage-collected.
It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
Python is often described as a "batteries included" language due to its comprehensive standard library.
原文はこちらです。
ファイルを読み込むにはファイルを開く、いわゆる open の処理が必要です。以下がファイル読み込みの流れになります。
f = open('text_file.txt')
print(f)
print(type(f))
f.close()
# <_io.TextIOWrapper name='text_file.txt' mode='r' encoding='cp932'>
# <class '_io.TextIOWrapper'>
open でファイルを開きファイルオブジェクトを変数 f に設定します。これにより変数 f を介してファイルにアクセスできます。この例では f の内容と f の type() を表示し最後に f.close() でファイルを閉じる処理を行います。
同じ処理を以下の with を使った方法で行ってみます。with() を使った方法では f.close() で行うファイルを閉じる処理が不要となります。
with open('text_file.txt') as f:
print(f)
print(type(f))
# <_io.TextIOWrapper name='text_file.txt' mode='r' encoding='cp932'>
# <class '_io.TextIOWrapper'>
ファイルの閉じ忘れはよくあることなので with を使った方法を用いることが多いです。このまとめでも今後は with を使った方法を用いていきます。ここまでがファイルを open するためのまとめです。
次に open したファイルから内容を読み込む方法です。Python でファイルを読み込むには以下の 3 つの方法があります。
read() : ファイル全体を文字列として読み込む
readlines():ファイル全体を1行を1つの要素としたリストとして読み込む。readlines() と末尾に複数行を示す s があることに注意
readline():1行単位で読み込む。全体を読み込むにはループ処理が必要。こちらは 1 行単位なので末尾に複数行を示す s がないことに注意
では順番に見ていきましょう。最初に read を使った以下の例を見てください。
with open('text_file.txt') as f:
data = f.read()
print(type(data))
print(data)
# <class 'str'>
#
# Python is an interpreted high-level general-purpose programming language.
# Python's design philosophy emphasizes code readability with its notable use of significant indentation.
# Its language constructs as well as its object-oriented approach aim to help programmers write clear,logical code for small and large-scale projects.
#
# Python is dynamically-typed and garbage-collected.
# It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
# Python is often described as a "batteries included" language due to its comprehensive standard library.
read() で読み込んだデータは文字列なので type を表示すると str になっています。また入力ファイルをそのまま読み込むので表示すると 1 つの文字列として表示されます。
次は readlines () で読み込んでみましょう。以下の例を見てください。
with open('text_file.txt') as f:
data = f.readlines()
print(type(data))
print(data)
for i in data:
print(i)
# <class 'list'>
#
# ['Python is an interpreted high-level general-purpose programming language.\n', "Python's design philosophy emphasizes code readability with its notable use of significant indentation.\n", 'Its language constructs as well as its object-oriented approach aim to help programmers write clear,logical code for small and large-scale projects.\n', '\n', 'Python is dynamically-typed and garbage-collected.\n', 'It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.\n', 'Python is often described as a "batteries included" language due to its comprehensive standard library.\n']
#
# Python is an interpreted high-level general-purpose programming language.
#
# Python's design philosophy emphasizes code readability with its notable use of significant indentation.
#
# Its language constructs as well as its object-oriented approach aim to help programmers write clear,logical code for small and large-scale projects.
#
#
#
# Python is dynamically-typed and garbage-collected.
#
# It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
#
# Python is often described as a "batteries included" language due to its comprehensive standard library.
readlines() で読み込んだデータは入力ファイルの1行を1つの要素とするリストとなっています。そのため type を表示すると list となっています。またリストを表示するとリストの要素単位で不要な改行が入っていることがわかります。元ファイル末尾の改行コードが読み込まれるためです。この改行コードが不要な場合は以下のように strip() 関数を使って末尾の改行コードを削除します。リストの要素単位での表示ができましたね。
with open('text_file.txt') as f:
data_strip = [line.strip() for line in f.readlines()]
print(type(data_strip))
print(data_strip)
for i in data_strip:
print(i)
# <class 'list'>
#
# ['Python is an interpreted high-level general-purpose programming language.', "Python's design philosophy emphasizes code readability with its notable use of significant indentation.", 'Its language constructs as well as its object-oriented approach aim to help programmers write clear,logical code for small and large-scale projects.', '', 'Python is dynamically-typed and garbage-collected.', 'It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.', 'Python is often described as a "batteries included" language due to its comprehensive standard library.']
#
# Python is an interpreted high-level general-purpose programming language.
# Python's design philosophy emphasizes code readability with its notable use of significant indentation.
# Its language constructs as well as its object-oriented approach aim to help programmers write clear,logical code for small and large-scale projects.
#
# Python is dynamically-typed and garbage-collected.
# It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
# Python is often described as a "batteries included" language due to its comprehensive standard library.
最後に readline() で 1行ずつ読み込んでみます。 以下の例をみてください。
with open('text_file.txt') as f:
while True:
data_line = f.readline()
print(data_line)
if not data_line:
break
# Python is an interpreted high-level general-purpose programming language.
#
# Python's design philosophy emphasizes code readability with its notable use of significant indentation.
#
# Its language constructs as well as its object-oriented approach aim to help programmers write clear,logical code for small and large-scale projects.
#
#
#
# Python is dynamically-typed and garbage-collected.
#
# It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.
#
# Python is often described as a "batteries included" language due to its comprehensive standard library.
readline() で1行ずつ読みこみますが while True: の無限ループを使っています。終了条件としてファイル末尾を検知するために not を使っています。readline() を使った場合も行末の改行が不要な場合不要な改行は strip で削除する必要があります。
この readline() による記述ですが、以下のように書いても同じ動作になります。よく見かけるのはこちらになるので readline() を使うことは少ないのでは、と思いますが必要な時に使ってください。
with open('text_file.txt') as f:
for data_line in f:
print(data_line)
今回はファイルの読み込みについてまとめました。
Python ファイルの読み書きに関するまとめの続きは以下からどうぞ。
では、ごきげんよう。