LoginSignup
12
8

More than 5 years have passed since last update.

pythonでEOFを明示的に取得する

Last updated at Posted at 2016-07-15

pythonでは,イテレーションでファイル読み込みをするため,明示的にファイルの読み込みの終了を示すEOFを意識することはありません.ですが,複数のファイルを同時処理する際にハマったので,EOFの取得方法を調べてみました.

ファイルオブジェクトのreadline()が空文字かを調べる方法

readline()の返り値が空文字のとき,EOFまで達しています.

# -*- coding: utf-8 -*-

#!/usr/bin/env python

filename = 'test.txt'

with open(filename,'r') as fi:
    while True:
        line = fi.readline()
        if not line:
            break

組み込み型のファイルオブジェクトのStopIterationを用いる方法

※python2.3以上,python3以下でしか動きません.

ファイルオブジェクトからnext関数を呼び出した場合,EOFに達するとStopIterationという例外が発生します.これを捉えることで,EOFを検知できます.

  # -*- coding: utf-8 -*-

  #!/usr/bin/env python

  filename = 'test.txt'

  with open(filename,'r') as fi
    while True:
        try:
            line = fi.next()
        except StopIteration: # EOFに到達
                break

参考リンク

12
8
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
12
8