I can basically replicate your sample with savetxt
. Its fmt
variable gives me the same sort of formatting control that FORTRAN code uses for reading and writing files. It preserves spaces in the same way that FORTRAN and C print does.
import numpy as np
example = """
This is a header. The first line is always a header...
7352.103 26.0 2.61 -8.397 11.2
...
"""
lines = example.split('\n')[1:]
header = lines[0]
data = []
for line in lines[1:]:
if len(line):
data.append([float(x) for x in line.split()])
data = np.array(data)
fmt = '%10.3f %9.1f %9.2f %9.3f %20.1f' # similar to a FORTRAN format statment
filename = 'stack21865757.txt'
with open(filename,'w') as f:
np.savetxt(f, data, fmt, header=header)
with open(filename) as f:
print f.read()
producing:
# This is a header. The first line is always a header...
7352.103 26.0 2.61 -8.397 11.2
7353.510 26.0 4.73 -1.570 3.5
...
EDIT
Here's a crude script that converts an example line into a format:
import re
tmplt = ' 7352.103 26.0 2.61 -8.397 11.2'
def fmt_from_template(tmplt):
pat = r'( *-?\d+\.(\d+))' # one number with its decimal
fmt = []
while tmplt:
match = re.search(pat,tmplt)
if match:
x = len(match.group(1)) # length of the whole number
d = len(match.group(2)) # length of decimals
fmt += ['%%%d.%df'%(x,d)]
tmplt = tmplt[x:]
fmt = ''.join(fmt)
return fmt
print fmt_from_template(tmplt)
# %10.3f%10.1f%10.2f%10.3f%29.1f