[Tutor] Blank line added after reading a line from a file

Jeff Shannon jeff@ccvcorp.com
Wed, 05 Dec 2001 10:34:11 -0800


> On Wed, 5 Dec 2001 12:29:55 -0000,
> "Kelly, Phelim" <KellyPhe@logica.com> wrote:

>
> The problem I have is that the text that is stored in variable 'text' isn't
> simply the contents of one line of the file, another blank line is appended
> onto the end, which causes problems for the rest of the program, so instead
> of this,
> ---------------------
> line read in from file
> --------------------
>
> I get this,
>
> -------------------
> line read in from file
>
> -------------------

The issue here is that, when readline() or readlines() reads in your file, it includes the newline character at the end of each line, in the returned string.  Then, presuming that you use the print statement to display your file, print automatically adds a newline at the end of its output.  Thus, it's not that blank lines are appended to what's read in, it's that they're added in when you print things out.  :)

The solution, as others have mentioned, is to use string.strip() on each line, either as you read it in or as you print it.  This will remove any extra whitespace at the start or end of the string.  You could also use string.rstrip() to remove whitespace only at the very end of the string, or use slice notation to chop off only the final character if you think that other whitespace may important to retain.  So, for example:

>>> # note that python uses '\n' to indicate newlines,
>>> # and reproduces them as '\012'
>>> mystring = "\n blah blah blah \n"
>>> # strip all surrounding whitespace
>>> mystring.strip()
'blah blah blah'
>>> # strip only from the right side
>>> mystring.rstrip()
'\012 blah blah blah'
>>> # use slice notation to get all but the last char
>>> mystring[:-1]
'\012 blah blah blah '
>>>

Hope that clarifies things a bit.  :)

Jeff Shannon
Technician/Programmer
Credit International