0

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

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
4

2 回答 2

0

您可以简单地将控制台输出重定向到文件 $python yourscript.py > output.txt

无需更改代码。

于 2013-09-17T02:43:56.640 回答
0

print函数有一个关键字参数file,它指定要写入的文件对象。这是最简单的方法:

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

您的代码不起作用的原因write是您没有在每个条目的末尾添加换行符。您也可以尝试修复:

file.write(' '.join(str(s) for s in point) + '\n')
于 2013-09-17T02:45:39.470 回答