File Iterator - Print - Double New Lines

Peter Hansen peter at engcorp.com
Sat Jun 1 22:03:05 EDT 2002


Mike Brenner wrote:
> 
> Peter wrote:
> > Mike, the print statement adds newlines after every line it prints.
> > If you want to see the real contents of the file, use sys.stdout.write().
> > Alternatively, you might want to strip the newlines from each line
> > as you read them in.  Depends what you are trying to do.

> That is not what happens, though. The first three outputs (from the first call 
> to reader) do not get newlines.  The second three outputs (from the second call 
> to reader) get double newlines.  The explanation that "the print statement adds 
> newlines after every lines it prints" would explain the double newlines the 
> second time, but it does not explain the lack of newlines the first time. 
> Did you run it on a windows machine?

Mike, I'm right, so study this before you respond again. <wink>

> def writer(list):
>     f=open("tmp.tmp","w")
>     for item in list:
>         f.write(item)
>     f.close()

Note that this routine never adds newlines.  Each item in the list
is written straight out as-is.  I'm glad you called them "items"
and not "lines", because they are not lines, as you'll see.

> def reader():
>     f=open("tmp.tmp","r")
>     for line in f:
>         print line
>     f.close()

Note that this routine reads "lines" which are by definition
sequences of bytes terminated with newlines, or the remaining
bytes terminated by EOF (if there's no final newline).

*Each line* printed by the print statement has a newline appended.
But you have only a single line in the first file!  See below for more 
on this.

> print "trying it without the \\n"
> writer(["a","b","c"])
> reader()

Here you are writing out three bytes, without any newlines.
When you read it back in, you get a single line of three bytes, 
again without even a newline, and then you print it (with one
newline appended by print).

> print "trying it with the \\n"
> writer(["a\n","b\n","c\n"])
> reader()

Here you deliberately force a newline after each byte, so
the file has the newlines present.  When you read with 
"for line in f", Python automatically splits the input
up into "lines", each one with a newline attached, because
there are now newlines in the file.

Then you print each of the *three* lines, with their
integral newlines, followed by the newline that print
appends.

To help you understand this, you might try examining
the files that are created with a binary editor.  You
could also change to using sys.stdout.write() which does
nothing funny with the output like print does.  You could
also experiment with repr() around the data, so you can
see the embedded newlines and such.

Cheers,
-Peter



More information about the Python-list mailing list