Numpy数组在python的数据分析中被广泛使用。在这篇文章中,我们将讨论如何在python中把Numpy数组保存到文本文件中。
使用str()函数将Numpy数组保存到文本文件中
我们可以使用str() 函数和文件处理将一个numpy数组保存到一个文本文件中。在这种方法中,我们将首先使用str() 函数将numpy数组转换为字符串。str() 函数将numpy数组作为输入参数并返回其字符串表示。 将numpy数组转换为字符串后,我们将把字符串保存到一个文本文件中。
为了将numpy数组保存到文本文件中,我们将首先使用open() 函数以追加模式打开一个文件。open() 函数将文件名作为其第一个输入参数,将字面意思 "a"作为第二个输入参数,以表示该文件是以追加模式打开的。执行后,它返回一个包含文本文件的文件对象。
得到文件对象后,我们将使用write() 方法将包含numpy数组的字符串保存到文件中。write() 方法在对文件对象调用时,将字符串作为其输入参数,并将字符串追加到文件中。将字符串写入文件后,别忘了用close() 方法关闭文件。
使用 str() 函数将一个numpy数组保存到一个文本文件的完整代码如下。
import numpy as np
myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
print("The content of the file before saving the array is:")
text = myFile.read()
print(text)
myFile.write(str(myArray))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)
输出。
The array is: [1 2 3 4 5 6 7 8 9]
The content of the file before saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
The content of the file after saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
[1 2 3 4 5 6 7 8 9]
使用numpy.savetxt()函数将Numpy数组保存到文本文件中
我们可以不使用str() ,而是使用numpy.savetxt() ,在python中把一个numpy数组保存到一个文本文件中。在这种方法中,我们首先使用open() 函数在追加模式下打开文本文件,正如在前面的例子中讨论的那样。打开文件后,我们将使用 numpy.savetxt() 函数将数组保存到文本文件中。这里,numpy.savetxt() 函数将文件对象作为其第一个输入参数,将numpy数组作为其第二个输入参数。执行后,它将numpy数组保存到文本文件中。你可以在下面的例子中观察到这一点。
import numpy as np
myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
np.savetxt(myFile, myArray)
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)
输出。
The array is: [1 2 3 4 5 6 7 8 9]
The content of the file after saving the array is:
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00
7.000000000000000000e+00
8.000000000000000000e+00
9.000000000000000000e+00
在,执行savetxt() 函数之后,你必须使用close() 对象关闭文件对象。否则,变化将不会被写入文件中。
总结
在这篇文章中,我们讨论了两种在Python中保存一个numpy数组到文本文件的方法。