Juanvulcano Juanvulcano - 1 month ago 6
Python Question

Python - How to write recursively without global var

I am working on a recursive function to write subcategories of a tree. I don't want to use a global var, what is the best way to write to the file on the recurse method?

def recurse(i):
Xmlfile = file("index.html", "w")
if i < 5:
Xmlfile.write(str(i))
recurse(i+1)
return(None)

def main():
Xmlfile = file("index.html", "w")
Xmlfile.write("I")
recurse(3)
Xmlfile.write("O")


The expected output should be something along the lines of: I 3 4 5 O, but I am only getting I O.

Answer

Pass it as an argument. The way you're doing it will reopen and truncate the file on every iteration.

def recurse(f, i):
    if i < 5:
        f.write(str(i))
        recurse(f, i+1)

def main():
    with open("index.html", "w") as xmlfile:
        xmlfile.write("I")
        recurse(Xmlfile, 3)
        xmlfile.write("O")

Note that I've replaced file() with the recommended open(), and have added a context manager to ensure the file gets closed.

Comments