Scanning a file

Jorge Godoy godoy at ieee.org
Fri Oct 28 09:35:08 EDT 2005


"pinkfloydhomer at gmail.com" <pinkfloydhomer at gmail.com> writes:

> Which is quite fast. The only problems is that the file might be huge.
> I really have no need for reading the entire file into a string as I am
> doing here. All I want is to count occurences this substring. Can I
> somehow count occurences in a file without reading it into a string
> first?

How about iterating through the file?  You can read it line by line, two lines
at a time.  Pseudocode follows:

line1 = read_line
while line2 = read_line:
      line_to_check = ''.join([line1, line2])
      check_for_desired_string
      line1 = line2

With that you always have two lines in the buffer and you can check all of
them for your desired string, no matter what the size of the file is.


Be seeing you,
-- 
Jorge Godoy      <godoy at ieee.org>



More information about the Python-list mailing list