TypeError: '_TemporaryFileWrapper' object is not an iterator
eryk sun
eryksun at gmail.com
Fri Jul 29 07:59:52 EDT 2016
On Fri, Jul 29, 2016 at 8:43 AM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
>
> The problem seems to come from my expectation that a file
> is its own iterator and in python3 that is no longer true
> for a NamedTemporaryFile.
For some reason it uses a generator function for __iter__ instead of
returning self, which would allow it to proxy the wrapped file's
__next__ method. There may be a good reason for that design decision,
but at the moment I don't see it, so I'd simply try the following:
import tempfile
import functools
class _TemporaryFileWrapper(tempfile._TemporaryFileWrapper):
def __iter__(self):
return self
def __next__(self):
return next(self.file)
@functools.wraps(tempfile.NamedTemporaryFile, assigned=['__doc__'])
def NamedTemporaryFile(*args, **kwds):
f = tempfile.NamedTemporaryFile(*args, **kwds)
f.__class__ = _TemporaryFileWrapper
return f
if __name__ == '__main__':
with NamedTemporaryFile('w+', prefix='tmptest-') as f:
for n in range(10):
f.write('This is line %d.\n' % n)
f.seek(0)
try:
while True:
print(next(f), end='')
except StopIteration:
pass
More information about the Python-list
mailing list