Reputation: 2718
I do this:
f = open('foo.txt', 'rb')
ii = (x for x in f.readlines())
f.close()
print(next(ii))
I see problem in my implementation of this code with use of iterator and calling next
after file is closed.
Is this implementation not problematic due to a fact of using iterator and executing on iterator after the file is closed regardless of no use of context manager?
Upvotes: 0
Views: 129
Reputation: 19143
No it isn't, because f.readlines()
is evaluated when the generator expression is created:
f = open('foo.txt', 'rb')
ii = (x for x in f.readlines())
print(f.tell()) # nonzero for non-empty file (shows how far we read)
f.close()
Note that, although we never call next
, the file's content has already been loaded.
Upvotes: 1