将屏幕输出重定向到文件中

时间:2013-09-17 02:41:05

标签: python-3.x

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

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

2 个答案:

答案 0 :(得分:0)

您只需将控制台输出重定向到文件即可 $ python yourscript.py > output.txt

无需更改代码。

答案 1 :(得分: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')