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

Andrei Kulakov ak@silmarill.org
Wed, 05 Dec 2001 13:41:40 -0500


On Wed, Dec 05, 2001 at 10:34:11AM -0800, Jeff Shannon wrote:
> > 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:

Another possible solution is to use readlines() because it simply makes
a list of lines, without adding "\n", and yet another solution is to add
a comma after the print statement, which prevents it from printing a
newline, like this:

print line,

I think readlines() is the cleanest way to deal with this problem..


> 
> >>> # 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
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org