0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでファイルを読み込む3つの方法

Posted at

Pythonを使ってテキストファイルを扱う際、ファイルの読み込み処理は非常に基本的でありながら重要な操作の一つです。本記事では、Pythonでテキストファイルを読み込む際によく使われる3つの方法、

  • read()
  • readline()
  • readlines()

について、それぞれの使い方や違いを具体例とともに解説します。


1. read()メソッド:ファイル全体を一括で読み込む

with open("my_file1.txt", "r") as f:
    content = f.read()
    print(content)

特徴

  • ファイルの内容をすべて1つの文字列として読み込みます。
  • サイズの指定をしなければ、全体を一括で読み込みます。
  • メモリにすべて読み込むため、大きなファイルには不向きです。

2. readline()メソッド:1行ずつ読み込む

with open("my_file1.txt", "r") as f:
    line1 = f.readline()
    print(line1)

特徴

  • ファイルの内容を1行ずつ順番に読み込みます。
  • ループ処理と組み合わせることで、行単位で柔軟な操作が可能。
  • メモリ効率がよく、大きなファイルにも適しています。
with open("my_file1.txt", "r") as f:
    for line in f:
        print(line.strip())

3. readlines()メソッド:すべての行をリストで取得

with open("my_file1.txt", "r") as f:
    content_l = f.readlines()
    print(content_l)

特徴

  • 各行を要素とするリスト形式で全体を一度に読み込みます。
  • 各要素が文字列として1行ずつ格納されているため、リスト処理が得意な場合に便利。
  • やはり、大きなファイルには注意が必要。

まとめ

メソッド 説明 向いているケース
read ファイル全体を一括で文字列として取得 小さめのファイルや全文処理したい場合
readline 一行ずつ読み込む 大きなファイル、逐次処理が必要な時
readlines 全行をリストとして一括取得 行ごとにまとめて扱いたい場合

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?