Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading