Explicitly get EOF in python

In python, the file is read by iteration, so there is no need to be aware of the EOF that explicitly indicates the end of file reading. However, I was addicted to processing multiple files at the same time, so I investigated how to get EOF.

How to check if readline () of a file object is empty

When the return value of readline () is an empty string, it has reached 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

How to use StopIteration for built-in file objects

If you call the next function from a file object, you will get an exception called StopIteration when EOF is reached. By catching this, EOF can be detected.

  # -*- coding: utf-8 -*-
    
  #!/usr/bin/env python

  filename = 'test.txt'

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

Reference link

Recommended Posts

Explicitly get EOF in python
Get date in Python
Get YouTube Comments in Python
Get last month in python
Get Evernote notes in Python
Get Japanese synonyms in Python
Get Leap Motion data in Python.
Get data from Quandl in Python
Get the desktop path in Python
Get the script path in Python
Get, post communication memo in Python
Get the desktop path in Python
Get the host name in Python
Get started with Python in Blender
Get additional data in LDAP with python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Get exchange rates from open exchange rates in Python
Get Suica balance in Python (using libpafe)
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Get Google Fit API data in Python
Sudoku in Python
DCI in Python
quicksort in python
N-Gram in Python
How to get a stacktrace in python
Programming in python
Get Youtube data in Python using Youtube Data API
Plink in Python
Constant in python
Get battery level from SwitchBot in Python
Get a token for conoha in python
Get Started with TopCoder in Python (2020 Edition)
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Get the EDINET code list in Python
Get Precipitation Probability from XML in Python
Get Cloud Logging available in Python in 10 minutes
Quad-tree in Python