开发者学堂课程【Python 常用数据科学库:文件读写】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/546/detail/7472
文件读写
使用 Numpy 读写数据
1、读写操作,以空格为分隔符
In [1]: import numpy as np
In [3]: %%writefile tang.txt
1 2 3 4 5 6
2 3 5 8 7 9
Writing tang.txt
//首先写出一个文件
In [5]: 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(cur_data)
data
In [12]: data = np. loadtxt ('tang. txt')
Data
2、读写操作,以逗号为分隔符
In [13]:%%writefile tang2.txt
1,2,3,4,5,6
2,3,5,8,7,9
Writing tang2.txt
In [15]:data = np. loadtxt(' tang2. txt', delimiter =',')
Data
//用逗号去写,就要指定一个逗号的分隔符
Out[15]: array([[ 1., 2., 3., 4., 5., 6.],
[2.,3.,5.,8.,7.,9.]])
In [16 ]:%%writefile tang2. txt
x,y,z,w,a,b
1,2,3,4,5,6
2,3,5,8,7,9
Overwriting tang2.txt
In [18]: data = np. loadtxt ('tang2. txt', delimiter =',', skiprows = 1)
data
Out[18]: array([[ 1., 2., 3., 4., 5., 6.],
[ 2.,3.,5.,8.,7.,9.]])
//tang2.txt':路径最好放到和代码一起
//skiprows:去掉几行
//delimiter=',':分隔符
//usecols=(0,1,4):指定使用哪几列