Dariusz Krynicki
Dariusz Krynicki

Reputation: 2718

python load file content with no context manager

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

Answers (1)

GPhilo
GPhilo

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

Related Questions