PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How to detect EOF when reading a file with readline() in Python?

 October 29, 2022     eof, exception, file, python, readline     No comments   

Issue

I need to read the file line by line with readline() and cannot easily change that. Roughly it is:

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        # I need to check that EOF has not been reached, so that readline() really returned something

The real logic is more involved, so I can't read the file at once with readlines() or write something like for line in i_file:.

Is there a way to check readline() for EOF? Does it throw an exception maybe?

It was very hard to find the answer on the internet because the documentation search redirects to something non-relevant (a tutorial rather than the reference, or GNU readline), and the noise on the internet is mostly about readlines() function.

The solution should work in Python 3.6+.


Solution

From the documentation:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        if not line:
            break
        # do something with line


Answered By - Barmar
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing