Scanning a file

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

Steven D'Aprano <steve at> wrote:
>On Fri, 28 Oct 2005 15:29:46 +0200, Björn Lindström wrote:
>> "pinkfloydhomer at" <pinkfloydhomer at> writes:
>>> f = open("filename", "rb")
>>> s =
>>> 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
- Tim Roberts, timr at
  Providenza & Boekelheide, Inc.

More information about the Python-list mailing list