TypeError: '_TemporaryFileWrapper' object is not an iterator

Terry Reedy tjreedy at udel.edu
Fri Jul 29 15:25:00 EDT 2016


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




More information about the Python-list mailing list