Opening and Printing files using Recursion in python
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 empt开发者_如何学Cy. 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])
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
精彩评论