gpt4 book ai didi

python - 重定向 sys.stdout 时 numpy savetxt 乱序

转载 作者:行者123 更新时间:2023-12-01 05:16:47 24 4
gpt4 key购买 nike

我想使用 numpy.savetxt 编写一个 numpy 数组,可以选择写入标准输出,或作为文件的一部分(通过重定向标准输出)。例如(在Python3中)

import numpy as np
import sys

def output( a ):
print( 'before np.savetxt' )
np.savetxt( sys.stdout.buffer, a )
print( 'after np.savetxt' )

a = np.array( [ ( 1, 2, 3 ), ( 4, 5, 6 ) ] )

output( a )

with open( 'test', 'w' ) as file_out:
sys.stdout = file_out
output( a )

这会写入(到标准输出):

before np.savetxt
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
after np.savetxt

但是“测试”文件包含这些乱序的条目:

> cat test
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
before np.savetxt
after np.savetxt

是否可以使这些输出保持一致的顺序,或者我应该使用不同的方法将 numpy.savetxt 与其他命令结合起来写入同一文件?

最佳答案

您只能在 output() 函数中使用 savetxt 命令,传递 headerfooter论据:

def output( a ):
header = 'before np.savetxt'
footer = 'after np.savetxt'
np.savetxt(sys.stdout.buffer, a, header=header, footer=footer)

正如 @DavidParks 所提醒的那样,对于 Python 2.7,它应该是 sys.stdout,对于 Python 3.x,它应该是 sys.stdout.buffer

关于python - 重定向 sys.stdout 时 numpy savetxt 乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23041516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com