Oct-12-2017, 12:13 PM
Just as a joke, but you can still learn about this.
Don't use this code.
The function
This works only, when the file has been opened in text mode. Calling
does the same what the for-loop does. The call
As you can see, there is no use of the returned data of
the end of file has been reached. The for-loop does get this Exception also and stops silently.
Don't use this code.
with open(file_name) as fd: lineiterator = iter(fd) for line in lineiterator: print(line.strip()) with contextlib.suppress(StopIteration): next(lineiterator)
fd
is the file object
.The function
iter(fd)
makes an iterator from the file object
.This works only, when the file has been opened in text mode. Calling
iter
on a file object,does the same what the for-loop does. The call
next(lineiterator)
jumps to the next line.As you can see, there is no use of the returned data of
next(lineiterator)
.contextlib.suppress
is just a context manager to suppress errors. In this caseStopIteration
is suppressed. If this Exception StopIteration
happend,the end of file has been reached. The for-loop does get this Exception also and stops silently.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!