Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

参考リンク

smdask
自然言語処理大好き人間です.フリーランスな研究者目指して、奮闘中.Emacs, mac, python
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした