recursive traversal of file

Hans Nowak hans at zephyrfalcon.org
Sat Aug 16 00:47:27 CEST 2003


Xavier Decoret wrote:
> I am reading the lines of a file, executing appropriate command if a 
> pattern is found. One of the pattern can be a input command whose effect 
> should be to #include the file (possibly recursively)
> 
> The main loop looks like this:
> 
> data=[]
> 
> try:
>     file = open(fileName)
>     line = file.readline()
>     while line:
>         if matchInputPattern(line,inputFile):
>              # help me here to parse inputFile
>         elif matchDataPattern(line):
>              data.append(1)
>         line = file.readline()
> except IOError, e:
>     print 'I couldn\'t open file name',fileName
>     sys.exit(1)
> 
> Can you tell me if there is a simple way to do the part that says #help 
> me!. Should I do a recursive function?

You could wrap all this in a function, let's call it import_file or whatever. 
Then, upon encountering the #include pattern, you could do,

   if matchInputPattern(line, inputFile):
       import_file(some_filename_extracted_from_pattern)

This *should* work, although I didn't test it.  Also, it assumes that recursive 
function calls share the same list ('data').  It would be cleaner to have 
import_file create, fill and return its own list.  In pseudocode:

def import_file(filename):
     data = []
     ...
     for line in lines:
        if (pattern matches):
            z = import_file(filename_from_pattern)
            data.extend(z)
        ...

     return data

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list