Learn how to save NumPy arrays to CSV files using np.savetxt() with formatting options, headers, and various delimiters for efficient data export.

Using NumPy’s savetxt method
Use np.savetxt() to export NumPy arrays to text files with customizable delimiters, formatting, headers, and comments for data storage and sharing.
To save an array to a CSV file, you need to use savetxt like in the example below:
import numpy as np
my_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape(3, 3)
np.savetxt("my_matrix.csv", my_array, delimiter=",")
print("CSV file saved successfully!") #Added feedback
Let’s break down the np.savetxt("my_matrix.csv", my_array, delimiter=",") syntax:
- The first argument,
"my_matrix.csv", is the file name. You can also specify a full path to the file here (e.g.,"path/to/my_matrix.csv"or"C:\\path\\to\\my_matrix.csv"on Windows). my_arrayis the NumPy array you want to save as a CSV.delimiter=","specifies the delimiter used to separate values in the CSV file. Since it’s a CSV file, we use a comma.
More Options with savetxt
The savetxt function offers more options for customizing the output:
import numpy as np
my_array = np.array([[1.12345, 2.67890], [3.14159, 4.00001]])
# Formatting floating-point numbers
np.savetxt("formatted_matrix.csv", my_array, delimiter=",", fmt="%.2f") #2 decimal places
# Adding a header and footer
header = "Column 1,Column 2"
footer = "End of data"
np.savetxt("header_footer_matrix.csv", my_array, delimiter=",", header=header, footer=footer, comments='') #comments='' removes the '#' before the header
# Saving integers
int_array = np.array([[1, 2], [3, 4]], dtype=int)
np.savetxt("int_matrix.csv", int_array, delimiter=",", fmt="%d")
#Different delimiter
np.savetxt("tab_separated.txt", my_array, delimiter="\t") #Tab separated
The comments parameter controls prefix characters: comments=” (no prefix), comments=’#’ (default), or comments=’@’ for custom prefixes before header/footer.
