Ever since Numpy 1.7.0, three parameters have been added to numpy.savetxt for exactly this purpose: header, footer and comments. So the code to do as you wanted can easily be written as:

import numpy
a = numpy.array([[0.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [1.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [2.0,1.630000e+01,1.990000e+01,1.840000e+01]])
fmt = ",".join(["%s"] + ["%10.6e"] * (a.shape[1]-1))
numpy.savetxt("temp", a, fmt=fmt, header="SP,1,2,3", comments='')
Answer from makhlaghi on Stack Overflow
🌐
Sharp Sight
sharpsight.ai › blog › numpy-savetxt
Numpy Savetxt, Explained - Sharp Sight
September 13, 2022 - Here, we’re going to add a header and footer to the output file. We’ll do that with the header and footer parameters: np.savetxt('my_numpy_data.txt' ,my_array ,header = 'This is header text' ,footer = 'This is footer text' )
Discussions

add option for header to savetxt (Trac #1079)
Original ticket http://projects.scipy.org/numpy/ticket/1079 on 2009-04-06 by trac user kkuhlman, assigned to unknown. To create symmetry with the skiprows option in loadtxt, it would make sense to have a header option in savetxt. This wo... More on github.com
🌐 github.com
8
October 19, 2012
savetxt should allow multi-line headers
I think it would be a useful addition if savetxt's header kwarg could optionally be a list, in which case multiple lines are added as header. The same could go for footer. What do you think? Us... More on github.com
🌐 github.com
1
November 18, 2014
python - Save structured numpy array using np.savetxt with header - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Then I tried to save it into a csv file using np.savetxt. I am wondering if there is way I could also save the label of each column as the header ... More on stackoverflow.com
🌐 stackoverflow.com
python numpy.savetxt header has extra character # - Stack Overflow
The header and footer text are added as comments. If you want to change the comment identifier, pass the comments option (the default is #): np.savetxt("foo.csv", x, delimiter=",", header="ID,AMOUNT", fmt="%i", comments='') As documented here. ... it inserts the # because that line is a comment, and the default character for comments is the symbol #, If you want to get rid of it, pass comments='' as option to savetxt. numpy... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-savetxt
numpy.savetxt() - GeeksforGeeks
December 13, 2018 - numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None) : This method is used to save an array to a text file.
🌐
GitHub
github.com › numpy › numpy › issues › 1677
add option for header to savetxt (Trac #1079) · Issue #1677 · numpy/numpy
October 19, 2012 - Original ticket http://projects.scipy.org/numpy/ticket/1079 on 2009-04-06 by trac user kkuhlman, assigned to unknown. To create symmetry with the skiprows option in loadtxt, it would make sense to have a header option in savetxt. This wo...
Author: numpy
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.savetxt.html
numpy.savetxt — NumPy v2.0 Manual
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)[source]#
🌐
Medium
medium.com › @heyamit10 › understanding-numpy-savetxt-with-code-examples-10d41aeaa209
Understanding numpy.savetxt() with Code Examples | by Hey Amit | Medium
April 18, 2025 - By default, numpy.savetxt() saves numbers with a lot of decimal places. But let’s be real—who needs 18 digits of precision for most tasks? If you want to simplify the output, use the fmt parameter. ... Notice how the decimals disappeared? That’s because fmt='%d' tells NumPy to format the numbers as integers. You can also use other formats like '%0.2f' for two decimal places. ... Want to add a bit of context to your saved file? You can include headers and footers.
🌐
GitHub
github.com › numpy › numpy › issues › 5290
savetxt should allow multi-line headers · Issue #5290 · numpy/numpy
November 18, 2014 - I think it would be a useful addition if savetxt's header kwarg could optionally be a list, in which case multiple lines are added as header. The same could go for footer. What do you think? Us...
Author: numpy
🌐
Python Guides
pythonguides.com › python-numpy-savetxt
Using Np.savetxt() In Python: Save NumPy Arrays To Text Files
May 16, 2025 - The np.savetxt() function is a NumPy utility that allows you to save array data to a text file. It’s particularly useful when you need to: Export data for use in other applications like Excel or MATLAB · Share results with colleagues who don’t use Python ... np.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
Find elsewhere
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.savetxt.html
numpy.savetxt — NumPy v2.5 Manual
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)[source]#
🌐
EDUCBA
educba.com › home › software development › software development tutorials › numpy tutorial › numpy savetxt
NumPy savetxt | How savetxt Function work in NumPy with Examples
April 19, 2023 - numpy.savetxt(file_name, Array, format='%.4e', delimiter=' ', newline='n', header=' ', footer=' ', comments='# ')
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GeeksforGeeks
geeksforgeeks.org › python › saving-numpy-arrays-to-text-files-using-numpy-savetxt
Saving NumPy Arrays to Text Files Using numpy.savetxt() - GeeksforGeeks
October 30, 2025 - numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
🌐
Stack Overflow
stackoverflow.com › questions › 50993993 › numpysavetxt-column-header
python - numpysavetxt column header - Stack Overflow
import numpy as np import string someData=np.random.random(size=(5,4)) # Edit: OP asked for numeric headers in the comments, # so here they are columnNames=["Type%d" % (i+1) for i in range(someData.shape[1])] # For the previous answer, uncomment both below # letters=string.ascii_uppercase # columnNames=["Type%s" % letter for letter in letters] # Index header columnNames.insert(0,"Index") rowIndices=np.arange(someData.shape[0]).reshape((-1,1)) # Make sure the first row are integers and the rest floats format="%i" format=format+",%.8f"*someData.shape[1] # Remember to remove the comment character! np.savetxt("mydata.csv", np.concatenate([rowIndices,someData], axis=1),fmt=format,comments='',header=','.join(columnNames))
🌐
NumPy
numpy.org › doc › 1.13 › reference › generated › numpy.savetxt.html
numpy.savetxt — NumPy v1.13 Manual
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ')[source]¶
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.savetxt.html
numpy.savetxt — NumPy v2.6.dev0 Manual
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)[source]#
🌐
Reddit
reddit.com › r/learnpython › a simply numpy.savetxt formatting issue is driving me crazy
r/learnpython on Reddit: A simply numpy.savetxt formatting issue is driving me crazy
September 18, 2018 -

I've narrowed my issue down to the following:

import numpy as np

out_file = "results.txt"
results = [[1,2,3,.4,"5"]] # just one row for testing
format = ['%i', '%i', '%i', '%f', '%s']

np.savetxt(out_file, results, format, '\t')

I'm just trying to save 5 columns of data: 3 ints, 1 float, and a string. When I attempt to so, I receive the error:

File ".\npyio.py", line 1391, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U32') and format specifier ('%i      %i      %i      %f      %s')

The code works just fine if I remove the string format and the corresponding value in the array.

This feels like one of those times that I'm just doing something really stupid, but after a couple hours of fruitless googling I think I need help.

Top answer
1 of 2
2
Thanks u/aldanor for figuring this out. Short version: you need to create a numpy array with column definitions because numpy doesn't actually take cues from the formatting string to determine a dtype. He also provided a good example of this . This morning, before he'd explained this to me, I realized that in my actual use case, I didn't really want to write a string column at all, but an arbitrary number of integer columns that I was going to format as a string rather than needing to always update the header & format for the output file. The arbitrary integer columns come from a set of parameters that I routinely add to and subtract from: # defines the minimum, maximum, and change step for each parameter that is permutated PARAM_DICT = { 'POINTS_PER_FREE_SQUARE': (1,60,10), 'ORDER_MULT': (1,20,1), 'DISORDER_MULT': (1,20,1), } I realized that I could get the new header line with simple string concatenation: fixed_headers = "Iteration\tSteps\tScore\tTime(s)\t" headers = fixed_headers + "\t".join(PARAM_DICT.keys()) And I could get the new format string using the * operator: dict_count = len(PARAM_DICT.items()) format = ['%i', '%i', '%i', '%f', *(['%i'] * dict_count)] So let's say I have a function that returns an array of results in that order: # some function that returns some fixed values (the iteration count, number of steps, etc.) as well as # all the values of the parameters for that iteration in the same order as PARAM_DICT def do_thing(x): return [x, 1, 20, 3.4, *(0 for _ in PARAM_DICT.keys())] I set the number of iterations and run that function to get an array of those results: iterations = 5 # or whatever results = [do_thing(x) for x in range(iterations)] And then I can save the text like I wanted without hard coding the headers or format: out_file = "results.txt" np.savetxt(out_file, results, format, '\t', header=headers) And if my parameters had different types, it would be pretty easy to just add the format to each dictionary item's tuple. Just goes to show that the answer you find isn't always the answer you end up using.
2 of 2
2
https://stackoverflow.com/a/35209070/1115659
🌐
SciPy
docs.scipy.org › doc › numpy-1.14.0 › reference › generated › numpy.savetxt.html
numpy.savetxt — NumPy v1.14 Manual
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)[source]¶