【问题标题】:Add a space in 2D array when writing a text file写入文本文件时在二维数组中添加一个空格
【发布时间】:2022-11-30 12:45:30
【问题描述】:

我正在尝试将 2D 矢量存储到 .DAT 文件中,我想在每一行的开头添加一个空格。所需输出的示例如下所示:

 0.0000000E+00  0.0000000E+00
 2.0020020E-03  0.0000000E+00
 4.0040040E-03  0.0000000E+00
 6.0060060E-03  0.0000000E+00
 8.0080080E-03  0.0000000E+00
 1.0010010E-02  0.0000000E+00
 1.2012012E-02  0.0000000E+00

可以看到0、2e-3、4e-3等前面有一个空格。我的代码正试图这样做

data = np.column_stack((x, y))
with open('output.dat', 'w') as datfile:
    for _ in range(N):
        np.savetxt(datfile, data, delimiter = "  ")

当前输出如下所示:

0.000000000000000000e+00  0.000000000000000000e+00
1.250156269533691795e-04  0.000000000000000000e+00
2.500312539067383591e-04  0.000000000000000000e+00
3.750468808601075386e-04  0.000000000000000000e+00
5.000625078134767181e-04  0.000000000000000000e+00
6.250781347668459519e-04  0.000000000000000000e+00
7.500937617202150772e-04  0.000000000000000000e+00

如您所见,每一行的前面都没有空格。你对此有什么解决方案吗?谢谢!

【问题讨论】:

    标签: python numpy numpy-ndarray genfromtxt


    【解决方案1】:

    使用循环和 f 字符串:

    import numpy as np
    
    data = np.zeros((5, 2), dtype=np.float64)
    
    with open("out.dat", "w") as fh:
        for row in data:
            x, y = row
            fh.write(f" {x}  {y}
    ")
    
     0.0  0.0
     0.0  0.0
     0.0  0.0
     0.0  0.0
     0.0  0.0
    

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2018-03-08
      • 2018-06-09
      • 2021-09-05
      • 1970-01-01
      相关资源
      最近更新 更多