如何将每个 for 循环输出添加到文件中

问题描述 投票:0回答:1
base_path = "/Users/charlesdaniel"
str_current_datetime = str(datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
current_file_name = str_current_datetime + ".txt"
print("\nFile created : ", current_file_name)
file_path = base_path + "/" + current_file_name
print("\nFull file path:", file_path)
time.sleep(3)

commands = ["sh version | include System image file", "show platform"]

    with open('file_path', 'a', encoding='utf-8') as f:
        for command in commands:
            cli_output = device_connection.send_command(command)
            print(cli_output)
            f.write(cli_output)f.close()

文件未创建,我如何添加该文件中保存的每个输出??

python file-operations-readdir
1个回答
0
投票

试试这个:

import time
from datetime import datetime

base_path = "/Users/charlesdaniel"
str_current_datetime = str(datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
current_file_name = str_current_datetime + ".txt"
print("\nFile created : ", current_file_name)
file_path = base_path + "/" + current_file_name
print("\nFull file path:", file_path)

time.sleep(3)

commands = ["sh version | include System image file", "show platform"]


with open(file_path, 'a', encoding='utf-8') as f:
    for command in commands:
        cli_output = f"Simulated output for {command}\n"  # Simulated output, remove when using real device
        print(cli_output)
        f.write(cli_output)
© www.soinside.com 2019 - 2024. All rights reserved.