Scanning a file
steve at REMOVETHIScyber.com.au
Sat Oct 29 01:41:54 CEST 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
f = open("filename", "rb")
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
More information about the Python-list