views:

77

answers:

1

So I am trying to write a code that opens a file and inside that file might be empty or contains the name of other files to open on each line. For example. 1.txt has 2.txt. on the first line and 3.txt on the second line. 2.txt is a empty file and 3.txt has 4.txt on the first line. I have to have an output that prints the files that the code runs through like "opening 1.txt..opening 2.txt and so on until all the files are open. the problem I am having is that my program stops printing when the opens the file that is empty. Looking at the example, I am not sure how to make it read the second line (3.txt) in 1.txt after it opened 2.txt and found out that it is empty.

The code I have so far is this: (this is an recursion problem):

def search(doc):
    a=open(doc)
    b=a.readline()
    if line == "":
        print ("Visiting  " + doc)

    else:
        print ("Visiting  " + doc)
        open(b[:-1])
        search(b[:-1])
+3  A: 

I am going to assume that a line contains the full path to the file. If this is not the case, then you should be able to make the necessary path modifications very easily. This IS homework, so I'll let you figure that out on your own

Try this:

def search(doc):
    print "Visiting", doc
    f = open(doc, 'r')
    for line in f:
        if line.strip():
            search(line.strip())

Cheers

inspectorG4dget
im new to recursion so i'm not sure if your code has any recursion in it. the way i learned it was that there needs to be a base case but i might be wrong.
Dan
@Dan you're right that there generally needs to be a base case when using recursion. There is a base case in this code, but it isn't explicit: when the file is empty, the body of the for loop is never executed, so you won't recurse any deeper.
Laurence Gonsalves