Pythonで大きなテキストファイルを読む方法

Pythonのファイルオブジェクトは、テキストファイルを読むためのさまざまな方法を提供しています。一般的な方法は、ファイル内のすべての行のリストを返すreadlines()メソッドを使用することです。しかし、大きなテキストファイルを読むのには適していません。なぜなら、ファイル全体の内容がメモリに読み込まれるからです。

Pythonで大きなテキストファイルを読む

ファイルオブジェクトをイテレータとして使用することができます。イテレータは一行ずつ返し、それぞれを処理することができます。この方法ではファイル全体をメモリに読み込む必要がなく、Pythonで大きなファイルを読み込むのに適しています。以下に、Pythonで大きなファイルをイテレータとして読み込むためのコードスニペットを示します。

import resource
import os

file_name = "/Users/scdev/abcdef.txt"

print(f'File Size is {os.stat(file_name).st_size / (1024 * 1024)} MB')

txt_file = open(file_name)

count = 0

for line in txt_file:
    # we can process file line by line here, for simplicity I am taking count of lines
    count += 1

txt_file.close()

print(f'Number of Lines in the file is {count}')

print('Peak Memory Usage =', resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
print('User Mode Time =', resource.getrusage(resource.RUSAGE_SELF).ru_utime)
print('System Mode Time =', resource.getrusage(resource.RUSAGE_SELF).ru_stime)

このプログラムを実行すると、生成される出力は次の通りです。

File Size is 257.4920654296875 MB
Number of Lines in the file is 60000000
Peak Memory Usage = 5840896
User Mode Time = 11.46692
System Mode Time = 0.09655899999999999
Python Read Large Text File
  • I am using os module to print the size of the file.
  • The resource module is used to check the memory and CPU time usage of the program.

この場合、ファイルを開くためにwith文を使うこともできます。その場合、ファイルオブジェクトを明示的に閉じる必要はありません。

with open(file_name) as txt_file:
    for line in txt_file:
        # process the line
        pass

大きなファイルに行がなかったらどうなりますか? (Ōkina fairu ni gyō ga nakattara dō narimasu ka?)

上記のコードは、大きなファイルの内容が多くの行に分割されている場合には非常に優れた動作をします。しかし、1行に大量のデータがある場合は多くのメモリを使用します。その場合、ファイルの内容をバッファに読み込んで処理することができます。

with open(file_name) as f:
    while True:
        data = f.read(1024)
        if not data:
            break
        print(data)

上記のコードは、1024バイトのバッファにファイルデータを読み込みます。その後、それをコンソールに出力しています。ファイル全体が読み込まれた時点で、データは空になり、break文でwhileループが終了します。この方法は画像やPDF、ワードドキュメントなどのバイナリファイルを読み込む際にも役立ちます。以下に、ファイルのコピーを作成するためのシンプルなコードスニペットがあります。

with open(destination_file_name, 'w') as out_file:
    with open(source_file_name) as in_file:
        for line in in_file:
            out_file.write(line)

参考元:StackOverflowの質問

Note: My answer is based on the assumption that you need a paraphrase of the sentence in Japanese.

参照:StackOverflowの質問

コメントを残す 0

Your email address will not be published. Required fields are marked *