Skip to main content
 首页 » 编程设计

Python savetxt 写为 int

2025年05月04日18zlslch

我正在尝试将一个数组写出到一个文本文件中,我希望每个元素都写成 int 类型。

我正在使用

np.savetxt(outfile_name, array, comments = '') 

写出文件。我使用

将 array 从 float 转换为 int
array = array.astype(int) 

当我在程序中打印 array 时,数组输出为 int,但是当我将其写入文本文件时,文件如下所示:

0.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 
1.000000000000000000e+00 1.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 
1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 0.000000000000000000e+00 
1.000000000000000000e+00 1.000000000000000000e+00 1.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 
1.000000000000000000e+00 1.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 

请您参考如下方法:

您是否尝试过根据 the documentation 指定格式?

np.savetxt(outfile_name, array, fmt="%d", comments='') 
                              # ^ format as signed decimal integer 

这使用标准 format specification mini-language .