[CentralOH] 2013-04-11 道場

Eric Floehr eric at intellovations.com
Fri Apr 12 22:18:18 CEST 2013


On Fri, Apr 12, 2013 at 4:01 PM, Kurtis Mullins <kurtis.mullins at gmail.com>wrote:

> On Fri, Apr 12, 2013 at 10:31 AM, Eric Floehr <eric at intellovations.com>wrote:
>
>>
>>
>> And if you are using Python 2.5 or higher, this is "best", as it closes
>> the file always, even on an exception:
>>
>> with open('foo', 'rU') as f:
>>     for line in f:
>>         # Do whatever with line or pass
>>
>
> That's actually what I use as well; however, I still have to check for
> blank lines. I assumed that's what jep was alluding to.
>

Not exactly, because a "blank line" returned from readline() (or the
iterator) signals end of file. A true "blank line" in a file will be
returned as '\n' since newlines aren't stripped when readline() reads the
line.

In other words '' (empty string) indicates EOF, while '\n' indicates an
empty line.

The iterator version handles it... when it gets an EOF it ends the
iteration, but if you readline() yourself, you have to check, otherwise
you'll forever get empty strings once the file is read.


For example (out of a script I recently wrote):
>
> with open(negation_lexicon_file_name, 'rb') as negation_file:
>     for line in negation_file:
>         phrase = line.strip().lower()
>         if phrase:
>             negation_lexicon['lexemes'].append(phrase)
>

Seems like a great way to do that.

-Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20130412/38f8629a/attachment-0001.html>


More information about the CentralOH mailing list