【问题标题】:How do I print a loop output iteration into a file?如何将循环输出迭代打印到文件中?
【发布时间】:2021-07-17 02:38:24
【问题描述】:

我正在尝试使用 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

我该怎么做?

【问题讨论】:

  • 请注意,print(...) 是一个返回(计算为)无的函数调用。我不确定这段代码是如何运行的,因为 for 块不会评估为可以用作函数参数的东西。

标签: python file dictionary


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    将参数从“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)
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 2020-07-28
      • 2012-06-12
      • 1970-01-01
      相关资源
      最近更新 更多