Scanning a file

Tim Roberts timr at probo.com
Sat Oct 29 23:08:09 CEST 2005


Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
>
>On Fri, 28 Oct 2005 15:29:46 +0200, Björn Lindström wrote:
>
>> "pinkfloydhomer at gmail.com" <pinkfloydhomer at gmail.com> writes:
>> 
>>> f = open("filename", "rb")
>>> s = f.read()
>>> sub = "\x00\x00\x01\x00"
>>> count = s.count(sub)
>>> print count
>> 
>> That's a lot of lines. This is a bit off topic, but I just can't stand
>> unnecessary local variables.
>> 
>> print file("filename", "rb").read().count("\x00\x00\x01\x00")
>
>Funny you should say that, because I can't stand unnecessary one-liners.
>
>In any case, you are assuming that Python will automagically close the
>file when you are done.

Nonsense.  This behavior is deterministic.  At the end of that line, the
anonymous file object out of scope, the object is deleted, and the file is
closed.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list