recursive traversal of file

X

Xavier Decoret

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?

--
+-------------------------------------------------+
| Xavier Décoret - Post Doct |
| Graphics Lab (LCS) - MIT |
| mailto: (e-mail address removed) |
| home : http://www.graphics.lcs.mit.edu/~decoret|
+-------------------------------------------------+
 
H

Hans Nowak

Xavier said:
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,
 
P

Paul McGuire

To prevent a recursive infinite loop, keep a list of the current chain of
filenames being imported. Before importing filename_from_pattern, make sure
it is not in the list (else you will eventually loop through the same files
until your stack blows up or similar dire consequence). If the file is in
the list, you can skip it, or raise an exception.

-- Paul McGuire
Austin, TX
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top