Python How to generate file name
Question: I was wondering if the community can help me out I'm a newbie to programming.
I trying to ssh to a list of devices contain on "list.txt" once it logs into
the router I send the same command to each one and write the output to a file.
However, on the code below it overrides the output of each device. I need to
create a unique file for each output with the name of the IP address that is
contains on the "list.txt" file. If anybody can help me out I would really
appreciated.

    
    
    import paramiko
    import time
    import os
    
    
    def disable_paging(remote_conn):
        '''Disable paging on a Cisco router'''
    
        remote_conn.send("terminal length 0\n")
        time.sleep(1)
    
        # Clear the buffer on the screen
        output = remote_conn.recv(1000)
    
        return output
    
    #Create variables
    f = open('list.txt')
    filepath = ('test/tas.txt')
    username = 'test'
    password = 'test'
    #Create a for loop 
    for i in f:
        remote_conn_pre = paramiko.SSHClient()
    
        remote_conn_pre.set_missing_host_key_policy(
                           paramiko.AutoAddPolicy())
    
        remote_conn_pre.connect(i, username=username, password=password)
    
        remote_conn = remote_conn_pre.invoke_shell()
    
        output = remote_conn.recv(1000)
    
        disable_paging(remote_conn)
    
        # Now let's try to send the router a command
        remote_conn.send("\n")
        remote_conn.send("show int des\n")
    
        # Wait for the command to complete
        time.sleep(2)
    
        output = remote_conn.recv(88880000)
    
        # print output
        if not os.path.exists(os.path.dirname(filepath)):
            os.makedirs(os.path.dirname(filepath))
        with open(filepath, "w") as f:
            f.write(output)
            f.close()
    


Answer: You could just have your 'filepath' variable defined in the for loop, and use
the 'i' string to create it :

    
    
    for i in f:
        filename = 'tas_%s.txt' % str(i)
        filepath = os.path.join('test', filename)
    
        # anything else remains unchanged
    

Hope it works (difficult without knowing the content of 'list.txt').

