Search code examples
pythonnumpynumpy-ndarraygenfromtxt

Add a space in 2D array when writing a text file


I am trying to store a 2D vector into a .DAT file and I would like to add a space at the start of every row. An example of a desired output looks like this:

 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

You can see at the front of 0, 2e-3, 4e-3, etc. there is a space. My code is trying to do that way

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

The current output looks like this:

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

As you can see, there is no space at the front of every line. Do you have any solutions for this? Thanks!


Solution

  • Use a loop and f-strings:

    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}\n")
    
     0.0  0.0
     0.0  0.0
     0.0  0.0
     0.0  0.0
     0.0  0.0