perl chomp equivalent in python?

Justin Sheehy dworkin at ccs.neu.edu
Thu Feb 10 15:46:13 EST 2000


Gerrit Holl <gerrit.holl at pobox.com> writes:

> > >>> for line in lines:
> >  print line[:-1]
> 
> Incorrect :(
> 
> >>> import os
> >>> lines = open("path-to-file", 'r').readlines()
> >>> for line in lines:
> ...     print line[:len(os.linesep)]

Also incorrect.  

Change 'len(os.linesep)' to '-len(os.linesep)' and it will do what I
think you meant.

Even with that correction, this solution will also not work in the
case where the last line does not have a trailing newline.  To see
what I mean, try that solution on a file created like this:

>>> open("path-to-file", 'w').write('spam%seggs' % os.linesep) 

You then have a file with two lines, but the second does not have a
terminating newline.  Stripping off the end of the line
indiscriminately will destroy some of the information in that second
line.

The need for this is also somewhat doubtful.  I have yet to see a real 
(not contrived) example where string.rstrip() wasn't the right choice
for this sort of thing.

-Justin

 




More information about the Python-list mailing list