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.
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
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
Recommended Posts