1.导入numpy
import numpy as np
2.写一个txt文件并保存
%%writefile tang.txt
1 2 3 4 5 6
2 3 5 8 7 9
3.将txt文件中的数据读取出来
data = []
with open('tang.txt') as f:
for line in f.readlines()://逐行读取
fileds = line.split()//将一行中每个数据分开
cur_data = [float(x) for x in fileds]
data.append(cur_data)
data = np.array(data)//转为ndarray
data
data = np.loadtxt('tang.txt')
data
4.loadtxt()中有一个delimeter参数需要注意,需要和文件中数字的分隔符相匹配
%%writefile tang2.txt
1,2,3,4,5,6
2,3,5,8,7,9
data = np.loadtxt('tang2.txt',delimiter = ',')
data
5.loadtxt()其他参数介绍
- 'tang2.txt':路径最好放到和代码一起
- skiprows : 去掉几行
- delimiter = ',' :分隔符
- usecols = (0,1,4) :指定使用哪几列
data = np.loadtxt('tang2.txt',delimiter = ',',skiprows = 1)
data
6.保存
tang_array = np.array([[1,2,3],[4,5,6]])
np.savetxt('tang4.txt',tang_array)
np.savetxt('tang4.txt',tang_array,fmt='%d')
np.savetxt('tang4.txt',tang_array,fmt='%d',delimiter = ',')
np.savetxt('tang4.txt',tang_array,fmt='%.2f',delimiter = ',')
7.保存的读写ndarray结构
tang_array = np.array([[1,2,3],[4,5,6]])
np.save('tang_array.npy',tang_array)
tang = np.load('tang_array.npy')
tang
8.保存的读写ndarray结构为压缩包
tang_array = np.array([[1,2,3],[4,5,6]])
np.save('tang_array.npy',tang_array)
tang = np.load('tang_array.npy')
tang
tang_array2 = np.arange(10)
tang_array2
np.savez('tang.npz',a=tang_array,b=tang_array2)
data = np.load('tang.npz')
data.keys()
data['a']
data['b']