Scanning a file

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Oct 28 19:41:54 EDT 2005


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. That's good enough for a script, but not best
practice.

f = open("filename", "rb")
print f.read().count("\x00\x00\x01\x00")
f.close()

is safer, has no unnecessary local variables, and is not unnecessarily
terse. Unfortunately, it doesn't solve the original poster's problem,
because his file is too big to read into memory all at once -- or so he
tells us.


-- 
Steven.




More information about the Python-list mailing list