Why doesn't this work? - comparing read lines from a file - string.replacequestion also.

Peter Hansen peter at engcorp.com
Sat Aug 31 00:46:55 CEST 2002


Micah Mayo wrote:
> for eachLine in open('rc.conf','r+'):
>     print orig,'\n',eachLine
[snip]
> and here is the result I get:
> 
> skipping
> sendmail_enable="YES"
> moused_type="NO"
> 
> skipping

Notice the extra blank line after "eachLine" is
printed, a line you didn't explicitly ask for.
This is coming from reading the file line by line,
which includes "\n" after each line.

If you don't care about trailing whitespace, you could
execute .rstrip() on each line (and on the string you're
comparing it to!).  Slightly more awkwardly, you could
do

    if eachLine[-1:] == '\n':
        eachLine = [:-1]

which would remove the trailing newline from each line,
except presumably the last if it doesn't have one.

By the way, I puzzled for a moment over your use of open()
like that.  I would think it would be more readable, if you
are going to use the file object's new ability to be iterated
over like that, if you created it with file() instead of open().

Otherwise pre-2.2 brains are likely to go looking for why you
didn't include .readlines() or something.

-Peter




More information about the Python-list mailing list