【问题标题】:write the screen output into the file将屏幕输出写入文件
【发布时间】:2013-09-16 22:25:37
【问题描述】:

我有一个关于将屏幕输出重定向到单个文件的问题。这是我打印屏幕输出的代码:

for O,x,y,z,M,n in coordinate:
    print(O,x,y,z,M,n)

屏幕输出如下:

O 0 0 0 ! 1
O 1 0 0 ! 2 
O 2 0 0 ! 3

那么我怎样才能将所有数据重定向到一个文件中并以相同的格式,就像屏幕输出一样。因为获取所有数据而不是等待屏幕输出完成会更快。 我试过for point in coordinate: file.write(' '.join(str(s) for s in point)),但输出文件变成了:

O 0 0 0 ! 0O 1 0 0 ! 1O 2 0 0 ! 2O 3 0 0 ! 3O 4 0 0 ! 4O 5 0 0 ! 5O 6 0 0 ! 6O

【问题讨论】:

  • 您应该缩小您的问题范围。无需粘贴所有代码,只需粘贴 coordinate 在所有这些循环结束时的样子。
  • 查看这个答案:stackoverflow.com/a/616686/5987

标签: python


【解决方案1】:

最简单的方法不是在 Python 中完成,而是让操作系统为您完成。这适用于 Linux 和 Windows 命令提示符。

python myprog.py >output.txt

【讨论】:

  • 在我看来这是处理这个问题的最好方法,当然除非你的程序的实际目标是将输出写入文件。那么在代码中处理它可能会更好,否则正确运行代码需要知道你必须像这样运行它。
  • @kniteli 我的目标是将所有屏幕输出重定向到一个文件中。我是python的新手,整天都在为这个问题苦苦挣扎。
【解决方案2】:

函数调用file.write(*point) 实质上获取point 列表中的每个元素,并将函数调用修改为如下所示:file.write(p1, p2, p3, p4, ...)

然而,file.write 只接受一个参数——一个字符串。这意味着您需要将point 列表转换为字符串。

它可能最终看起来像这样:

with open('substrate', 'w') as file:
    for point in coordinate:
        file.write(' '.join([str(p) for p in point])

【讨论】:

    【解决方案3】:

    试试

    with open('substrate', 'wb') as file:
        file.write('\n'.join(' '.join(str(p) for p in point)) for point in coordinate)
    

    如果您想知道为什么wb?见this question

    如果您想使用Mark Ransom 的答案,我相信您在代码中就是这样做的:

    from sys import stdout
    stdout.write('\n'.join(' '.join(str(p) for p in point)) for point in coordinate)
    

    【讨论】:

    • 我试过你的代码。但是我我的输出文件只包含:s s ss s等
    • @JianliCheng 好吧,看来你用的是python 3。查看更新代码
    • 输出文件仍然不是我要找的。在输出文件中,n 跳转到 10,然后是 20,30,40 等,不是 1,2,3,4,5...还有,如何让输出文件中的每一行都只被占用一点,比如:O 0 0 0 ! 1/n O 1 0 0! 2/n
    • @JianliCheng 使用您使用此代码时在文件中获得的输出更新您的原始帖子
    • @JianliCheng 我知道你的问题出在哪里,我会在一分钟内更新我的帖子
    【解决方案4】:

    不完全确定你在寻找什么,所以我要走两条路。

    for coordset in coordinate:
        for point in coordset:
            file.write(point)
    

    或者,如果你想要格式化,你可以使用格式化字符串。

    for coordset in coordinate:
        file.write('%s,%s,%s,%s,%s,%s' % set)
    

    如果我理解错了,你可以澄清你的帖子。

    【讨论】:

    • 注意set是python中的关键字。因此,您可能不得不考虑将该名称更改为更适合此的其他名称
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多