I read a file which only contains one line. However, I can’t stop reading the file until the loop end. i.e. the python doesn’t throw EOFError exception. what’t wrong with my code?
for x in range(5):
try:
line = file.readlines()
except EOFError:
break
print "Line:",line
The output is:
Line: ['nice\n']
Line: []
Line: []
Line: []
Line: []
readlines()reads the whole document and returns the list of lines, not just a single line.You probably meant to use
file.readline()– but even that does not raise an error, so you have to do something else, like checkingif not line.endswith("\n"): breakorlen(line) < 1to detect the EOF.Personally I would write the same functionality something like:
Or if you want to get rid of the extra newlines, change the print statement to: