如何将NumPy数组保存为文本文件
让我们看看如何将一个numpy数组保存到一个文本文件。
方法1:使用文件处理
使用内置的open()函数创建一个文本文件,然后将数组转换为字符串,并使用write()函数将其写入文本文件中。最后使用close()函数关闭该文件。下面是这种方法的一些程序。
- 示例 1:
# Program to save a NumPy array to a text file
# Importing required libraries
import numpy
# Creating an array
List = [1, 2, 3, 4, 5]
Array = numpy.array(List)
# Displaying the array
print('Array:\n', Array)
file = open("file1.txt", "w+")
# Saving the array in a text file
content = str(Array)
file.write(content)
file.close()
# Displaying the contents of the text file
file = open("file1.txt", "r")
content = file.read()
print("\nContent in file1.txt:\n", content)
file.close()
- 输出:
Array:
[1 2 3 4 5]
Content in file1.txt:
[1 2 3 4 5]
- 示例 2:
# Program to save a NumPy array to a text file
# Importing required libraries
import numpy
# Creating 2D array
List = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Array = numpy.array(List)
# Displaying the array
print('Array:\n', Array)
file = open("file2.txt", "w+")
# Saving the 2D array in a text file
content = str(Array)
file.write(content)
file.close()
# Displaying the contents of the text file
file = open("file2.txt", "r")
content = file.read()
print("\nContent in file2.txt:\n", content)
file.close()
- 输出:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Content in file2.txt:
[[1 2 3]
[4 5 6]
[7 8 9]]
- 示例 2:
使用NumPy函数
在创建数组后,
numpy.savetxt()
函数可以用来将数组保存到一个文本文件中。下面是这种方法的一些程序。
- 示例 1:
# Program to save a NumPy array to a text file
# Importing required libraries
import numpy
# Creating an array
List = [1, 2, 3, 4, 5]
Array = numpy.array(List)
# Displaying the array
print('Array:\n', Array)
# Saving the array in a text file
numpy.savetxt("file1.txt", Array)
# Displaying the contents of the text file
content = numpy.loadtxt('file1.txt')
print("\nContent in file1.txt:\n", content)
- 输出:
Array:
[1 2 3 4 5]
Content in file1.txt:
[1. 2. 3. 4. 5.]
- 示例 2:
# Program to save a NumPy array to a text file
# Importing required libraries
import numpy
# Creating 2D array
List = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Array = numpy.array(List)
# Displaying the array
print('Array:\n', Array)
# Saving the 2D array in a text file
numpy.savetxt("file2.txt", Array)
# Displaying the contents of the text file
content = numpy.loadtxt('file2.txt')
print("\nContent in file2.txt:\n", content)
- 输出:
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Content in file2.txt:
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]