📜  numpy.savetxt()

📅  最后修改于: 2022-05-13 01:54:24.551000             🧑  作者: Mango

numpy.savetxt()

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None) : 这个方法用于将数组保存到文本文件。

代码#1:

# Python program explaining  
# savetxt() function
import numpy as geek
  
x = geek.arange(0, 10, 1)
print("x is:")
print(x)
  
# X is an array
c = geek.savetxt('geekfile.txt', x, delimiter =', ')   
a = open("geekfile.txt", 'r')# open file in read mode
  
print("the file contains:")
print(a.read())

输出 :

x is:
[0 1 2 3 4 5 6 7 8 9]
the file contains:
0.000000000000000000e+00
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


代码#2:

# Python program explaining  
# savetxt() function
  
import numpy as geek
  
x = geek.arange(0, 10, 1)
y = geek.arange(10, 20, 1)
z = geek.arange(20, 30, 1)
print("x is:")
print(x)
  
print("y is:")
print(y)
  
print("z is:")
print(z)
  
# x, y, z are 3 numpy arrays with same dimension 
c = geek.savetxt('geekfile.txt', (x, y, z)) 
a = open("geekfile.txt", 'r')# open file in read mode
  
print("the file contains:")
print(a.read())

输出 :


代码 #3:类型错误

# Python program explaining  
# savetxt() function
  
import numpy as geek
  
x = geek.arange(0, 10, 1)
y = geek.arange(0, 20, 1)
z = geek.arange(0, 30, 1)
print("x is:")
print(x)
  
print("y is:")
print(y)
  
print("z is:")
print(z)
  
# x, y, z are 3 numpy arrays without having same dimension 
c = geek.savetxt('geekfile.txt', (x, y, z)) 

输出:

请注意,如果 numpy 数组的维度不相等,则会发生错误。