[Tutor] Writing to output file

Jon Cosby jlcos@accessone.com
Thu, 25 Mar 1999 12:35:14 -0800

This should be an easy one, but I'm not finding it: How do you print to an
output file? I'm trying to get the results of search.py below on a text
file. Nothing I've tried seems to work.
Maybe somebody can tell me why it's so slow, too; it took it 15 minutes to
search a 115 MB archive.

Jon Cosby

# Search.py
# Counts (case-insensitive) instances of string in a given directory and
it's sub-directories
# To-do: Include file names in the search; search multiple strings

import re, sys, os

def searchtext(filename, text):
     line = "initialized"
     infile = open(filename, 'r')
     outfile = open('c:\\data\\results.txt', 'w')
     a = []
     while line != "":
          line = infile.readline()
          b = re.compile(text, re.I).findall(line)
          if len(b) > 0:
     if len(a) > 0:
         print filename, text, ':', len(a)     # I want to write this to
     else:                                                # Seems like a
simple problem, but the
         return 0                                     # documents only give
 infile.close()                                     # for writing a string.

def getFile(dir, text):
     dl = os.listdir(dir)
     for i in range(len(dl)):
        dl[i] = dir + '\\' + dl[i]
        if os.path.isfile(dl[i]):
            searchtext(dl[i], text)
            getFile(dl[i], text)

if __name__ == '__main__':
     getFile(sys.argv[1], sys.argv[2])