如何将循环输出迭代打印到文件中?

时间:2021-04-22 20:53:07

标签: python file dictionary

我正在尝试使用 python 将循环输出保存到文本文件中。但是,当我尝试这样做时,只有结果的第一行会打印在文件上。

这是我想打印结果的行:

with open('myfile.txt','w') as f_output:
       f_output.write(
           for k, v in mydic.items():
               print(f"{k:11}{v[0]}{v[1]:12}"))

这仅打印结果的第一行。

我的字典是这样的:

mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}

我需要将其打印到文件中:

1          22      23
2          33      24
3          44      25

我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用 a 以追加模式写入:

mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}

with open('myfile.txt','a') as f_output:
    for k, v in mydic.items():
        # Also need `\n` for newlines:
        f_output.write(f"{k:11}{v[0]}{v[1]:12}\n")

输出:

1          22          23
2          33          24
3          44          25

答案 1 :(得分:1)

将参数从“w”(写入)更改为“a”(附加)。

mydic = {'1': [22, 23], '2': [33, 24], '3': [44, 25]}

with open('myfile.txt','a') as f_output:
    for k, v in mydic.items():
        res=f"{k:11}{v[0]}{v[1]:12}"
        f_output.write(f"{res}\n")
        print(res)

相关问题