'How to save each forloop output into separated file name not in a single file name?

I want to save each output of "forloop" into different text file, not in a single text file. Like for example. First loop output will be in Device1_Output01.txt, Second loop output will be in Device2_Output02.txt, Device3_Output03.txt, etc. Please help me I'm a beginner. Appreciate your help in advance. Thank you.

import paramiko
import time
import sys


c = open("Command_List.txt", "r")
command_list = c.read().split("\n")    /*Create a List from Command_List file */

        
d = open("Device_List.txt", "r")
nodes = d.read().split("\n")           /*Create a List from Device_List file */                  



port = 22
username = "user"
password = "password"

for ip in nodes:              /*Loop each ip in hosts list */                    
    print("Login to:", ip)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, password)
    comm = ssh.invoke_shell()

    for command in command_list:           /*Loop each commmand in command_list    
        comm.send(' %s \n' %command)
        time.sleep(.5)
        output = comm.recv(9999)
        output = output.decode('ascii').split(',')   /*Convert string to List without any change*/

        restorepoint = sys.stdout
        sys.stdout = open('HWOutput.txt', "a")   /*All output will be appended here. How will I save each forloop output into different filenames?.*/
        print(''.join(output))
        sys.stdout = restorepoint

ssh.close()


Solution 1:[1]

Just replace sys.stdout with an actual open file at the start of the loop, then close the file and revert back to initial stdout at the end.

for ip in nodes:
    if not ip.strip(): continue
    with open(ip + ".ssh-log.txt","wt") as sshlog:
        sys.stdout = sshlog
        print("Login to:", ip)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, port, username, password)
        comm = ssh.invoke_shell()
        for command in command_list:
            comm.send(' %s \n' %command)
            time.sleep(.5)
            output = comm.recv(9999)
            output = output.decode('ascii').split(',')
            print(''.join(output))
    sys.stdout = sys.__stdout__

ssh.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1