File read from stdin and printed to temp file are not identicial?

MRAB python at mrabarnett.plus.com
Thu Sep 16 20:06:08 EDT 2010


On 17/09/2010 00:36, Jean Luc Truchtersheim wrote:
> Hello,
>
> I am trying to read from stdin and dump what's read to a temporary
> file. My code works for small files but as soon as I have a file that
> has, e.g., more than 300 lines, there is always one and only one line
> that is truncated compared to the input.
>
> Here is my code:
> #---------------------------------------------------------------------------------
> #! /usr/bin/env python
>
> import sys
> from tempfile import *
>
> if __name__ == "__main__":
> 	data = []
> 	f_in = NamedTemporaryFile(suffix=".txt", delete=False)
> 	for line in sys.stdin:
> 		f_in.write(line)
> 		data.append(line)
> 	f_in.close
> 	f = open(f_in.name, 'rb')
> 	i=0
> 	for line in f:
> 		if data[i] != line:
> 			print>>sys.stderr, "line %d:\nfile(%d):\"%s\"\narray(%d):\"%s\"" %
> (i+1, len(line), line, len(data[i]), data[i])
> 		i += 1
> 	sys.exit()
> #-------------------------------------------------------------------------------------------------
>
> I feel that I must be doing something very stupid, but I don't really
> know what.
>
> Any idea?
>
> Can anybody reproduce this behavior.
>
> Thanks a bunch for any help.
>
> Jean Luc.

You're not closing f_in. That line should be:

     f_in.close()



More information about the Python-list mailing list