Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #112026
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: TypeError: '_TemporaryFileWrapper' object is not an iterator |
| Date | 2016-07-29 15:25 -0400 |
| Message-ID | <mailman.34.1469820307.6033.python-list@python.org> (permalink) |
| References | <5798BECB.8030800@rece.vub.ac.be> <579B1720.9000103@rece.vub.ac.be> <nngaic$obp$1@ger.gmane.org> |
On 7/29/2016 4:43 AM, Antoon Pardon wrote:
> Below is a short program that illustrate the problem
> It works with python2, whether you use the -c option or not.
> It only works with python3 if you use the -c option.
>
> 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.
As Eryk Sun said, a _TemporaryFileWrapper is an iterable, but not an
iterator.
> Should this be considered a bug?
No. The doc for NamedTemporaryFile does not even claim that the return
is iterable.
> =========================================================================
>
> from tempfile import NamedTemporaryFile
> import sys
>
> def main(tmp):
> write = sys.stdout.write
> if tmp:
> tstfl = NamedTemporaryFile("w+", prefix = 'tmptest-')
> else:
> tstfl = open("Temporary", "w+")
>
> for nr in range(10):
> tstfl.write("This is line %d\n" % nr)
>
> tstfl.seek(0)
Either add "tstfl_it = iter(tstfl)" and call next on what is now
guaranteed to be an iterator, if one is possible.
> try:
> while True:
> ln = next(tstfl)
> write(ln)
> except StopIteration:
> pass
Or replace the above with the much easier to write and more idiomatic
for line in tstfl:
write(line)
> if __name__ == "__main__":
> tmp = True
> if len(sys.argv) > 1:
> # if -c option is passed a normal file will be
> # used instead of a NamedTemporaryFile
> if sys.argv[1] == '-c':
> tmp = False
> main(tmp)
>
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: TypeError: '_TemporaryFileWrapper' object is not an iterator Terry Reedy <tjreedy@udel.edu> - 2016-07-29 15:25 -0400
csiph-web