【问题标题】:How to write the output of a python in a text file in separated lines?如何在单独的行中将python的输出写入文本文件?
【发布时间】:2019-07-19 06:32:52
【问题描述】:

我想将我的 phyton 程序的输出写入一个文本文件。输出在一个循环中,我希望每个输出都在一行中。我正在使用此代码进行编写,但我仍将在一行中给出所有结果。

with open('temp.txt', 'w') as outfile:
    out = P2[16:3276,:].sum(axis=0)
    outfile.write("{}\n".format(out))

实际结果是:

[ 0.  0.  0. ...,  0.  0.  0.]

但我想变成这样:

0
0
0
0
0
0

【问题讨论】:

    标签: python text output


    【解决方案1】:

    改用str.join

    with open('temp.txt', 'w') as outfile:
        out = P2[16:3276,:].sum(axis=0)
        outfile.write("\n".join(map(lambda x: '%f' % x, out)))
    

    【讨论】:

    • 谢谢。但我的输出是 mot 字符串。使用此代码,我将遇到此错误:序列项 0:预期的 str 实例,找到 numpy.float32
    • 我没有否决您的回答。这对我来说是-1,所以我没有。
    • @Zahra 立即尝试。
    • 谢谢。它现在正在工作。但是对于一些输出,我会有像“3.23108e-08”这样的科学数字。你我怎么能避免这个,只有一些浮点数?
    【解决方案2】:

    你可以使用替换,取决于你的输出,但它可以工作

    r = { "[": "", ".": "\n", "]": ""}
    
    for x,y in r.items():
            out = out.replace(x, y)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 2023-04-05
      • 2013-11-02
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多