📜  numpy savetext - Python (1)

📅  最后修改于: 2023-12-03 15:18:03.082000             🧑  作者: Mango

NumPy savetext - Python

NumPy is the fundamental package for scientific computing in Python. It is a library that provides support for multidimensional arrays, as well as mathematical functions to operate on these arrays.

One of the many functionalities that NumPy offers is the ability to save arrays to text files with the numpy.savetxt function.

Syntax

The syntax for the numpy.savetxt function is as follows:

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)

where:

  • fname: String, file, or file-like object. The name of the file to which the data is saved. If fname is a string, the file is created with that name; otherwise, fname is assumed to be a file-like object and the data is saved to it directly.
  • X: Array_like, data to be saved to a text file.
  • fmt: String or sequence of strings, optional. A single format (%-style) string specifying how to format each column. For example, '%d' for integers, '%f' for floating point numbers, and '%s' for strings. Alternatively, this can be a list of format specification strings, one for each column. If not specified, fmt='%.18e' (i.e., scientific notation with 18 digits of precision) is used by default.
  • delimiter: String, optional. The string used to separate values. By default, this is a space (' ').
  • newline: String, optional. The string to be used to terminate lines. By default, this is a newline ('\n').
  • header: String, optional. String that is written at the beginning of the file.
  • footer: String, optional. String that is written at the end of the file.
  • comments: String, optional. String that is prepended to header and footer lines.
Example
import numpy as np

# create a 2D array
a = np.array([[1, 2, 3], [4, 5, 6]])

# save the array to a text file
np.savetxt('example.txt', a, fmt='%d', delimiter=',')

# load the array from the text file
b = np.loadtxt('example.txt', delimiter=',')

# print the original and loaded arrays
print('Original array:')
print(a)
print('Loaded array:')
print(b)

In this example, we create a 2D NumPy array a with two rows and three columns. We then save this array to a text file named example.txt using the numpy.savetxt function with a format specifier of '%d' (i.e., integers). We also specify ',' as the delimiter to separate the values in the file.

We then use the numpy.loadtxt function to load the array b from the same text file. Finally, we print both the original array a and the loaded array b.

Conclusion

NumPy's savetext function provides a convenient way to save arrays to text files, which can later be loaded using the loadtxt function. With a wide range of customization options, this function is a powerful tool for data storage and retrieval in scientific computing projects.