投稿

[Python 100日チャレンジ] Day 42 - テキストファイルの応用処理

Pythonで大きなテキストファイルを1行ずつ読み、検索、フィルタ、整形を行う方法を学びます。

[Python 100日チャレンジ] Day 42 - テキストファイルの応用処理

1行ずつ読む

大きなファイルは、全部を一度に読むより1行ずつ処理する方が安全です。

1
2
3
with open("log.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

条件で絞り込む

1
2
3
4
with open("log.txt", "r", encoding="utf-8") as file:
    for line in file:
        if "ERROR" in line:
            print(line.strip())

ログやCSVの前処理では、このような絞り込みがよく出ます。

整形して保存する

1
2
3
4
with open("input.txt", "r", encoding="utf-8") as src, \
     open("output.txt", "w", encoding="utf-8") as dst:
    for line in src:
        dst.write(line.strip().lower() + "\n")

今日のゴール

テキストファイルは1行ずつ処理できるようになると、検索、抽出、整形がしやすくなります。小さなログ処理から練習しましょう。

この投稿は投稿者によって CC BY 4.0 の下でライセンスされています。