Python Forum

Full Version: with open context inside of a recursive function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm writing code to check various routers, part of it includes checking the traffic statistics, which is parsed per router. So I need either an open('file.txt')

or a with open context. I decided to stick with the context assuming it would be open until the entire program executed. The brlow for loop gets called by an outer function which is reccursed. Is this with context okay usage?


 for intf in interface_list:
            show_intf = "show interface {}".format(intf)
            result = ConnectHandler.send_command(show_intf)
            rate = re.search(input_rate, result)
            bandwidth = re.search(bw_template, result)
            if int(rate.group("rate")) / int(bandwidth.group("bandwidth")) >= 0:
                with open()
                updated_interfaces.append(intf)
or should I stick with traditional open, close
Is the idea that you want to write values to file.txt and you want the file to stay open, but close when you are done?
def recursive_function(statistics, args):
    # Do router stuff
    # Write information to statistics

with open("file.txt", "w") as statistics:
    recursive_function(statistics, args)