Python读取文件小结(csv,txt)
2016-07-04 14:15
666 查看
搞了半天终于把Python读取文件的方式搞定了,这里简单说下
1. 使用open
不过这里需要注意的是,line的格式为str,所以我其实并不喜欢这种方式,而且我感觉这种
我觉得应该有其他的方式把txt读取成list,但暂时不想搞了,所以就不整了
2. 使用csv(强行把txt改成csv文件)
我觉得这样才是我比较喜欢的方式,
1. 读取csv文件
2. temp为csv.reader类型
3. 按row读取temp中的东西
4. 注意这里header,如果csv中直接都是数据(相当于header已知),则可以不用header,否则需要加header
3. np.loadtxt()
<span style="font-size:18px;">import numpy as np
data = np.loadtxt("E:\\ML\\machine-learning-ex2\\machine-learning-ex2\\ex2\\ex2data1.csv",delimiter = ',')</span>
感觉这种方法强无敌好吧,一步到位,不过需要注意的是逗号。
参考博客:
1. http://python3-cookbook.readthedocs.io/zh_CN/latest/c06/p01_read_write_csv_data.html
2. http://www.cnblogs.com/sysuoyj/archive/2012/03/14/2395789.html
1. 使用open
<span style="font-size:18px;">f = open("E:\\ML\\machine-learning-ex2\\machine-learning-ex2\\ex2\\ex2data1.csv") line = f.readline() while line: print line line = f.readline() f.close()</span>
不过这里需要注意的是,line的格式为str,所以我其实并不喜欢这种方式,而且我感觉这种
我觉得应该有其他的方式把txt读取成list,但暂时不想搞了,所以就不整了
2. 使用csv(强行把txt改成csv文件)
<span style="font-size:18px;"></span><pre style="font-family: 宋体; font-size: 11.3pt; background-color: rgb(255, 255, 255);"><pre name="code" class="python">import csv import numpy as np data = [] with open("E:\\ML\\machine-learning-ex2\\machine-learning-ex2\\ex2\\ex2data1.csv") as f: temp = csv.reader(f) #headers = next(temp) for row in temp: data.append(row)
我觉得这样才是我比较喜欢的方式,
1. 读取csv文件
2. temp为csv.reader类型
3. 按row读取temp中的东西
4. 注意这里header,如果csv中直接都是数据(相当于header已知),则可以不用header,否则需要加header
3. np.loadtxt()
<span style="font-size:18px;">import numpy as np
data = np.loadtxt("E:\\ML\\machine-learning-ex2\\machine-learning-ex2\\ex2\\ex2data1.csv",delimiter = ',')</span>
感觉这种方法强无敌好吧,一步到位,不过需要注意的是逗号。
参考博客:
1. http://python3-cookbook.readthedocs.io/zh_CN/latest/c06/p01_read_write_csv_data.html
2. http://www.cnblogs.com/sysuoyj/archive/2012/03/14/2395789.html
相关文章推荐
- 使用Python学习selenium测试工具-6:同步
- python INFO: Can't locate Tcl/Tk libs and/or headers
- 使用Python学习selenium测试工具-5:元素交互
- python深浅拷贝探究
- Json概述以及python对json的相关操作
- python中字符串的使用方法
- Python函数式编程指南(三):迭代器
- mac下python安装lxml失败
- 基于树的建模-完整教程(R & Python)
- python爬虫(一)
- leetcode-python 第一周
- python调用jar包类
- 通过“生产者-消费者模型”理解Python协程和yield关键字
- python CRC32-mpeg2校验
- API例子:用Python驱动Firefox采集网页数据
- python小打小闹之简陋版BBS
- 使用Python学习selenium测试工具-4:查找元素
- 解决mac osx下pip安装ipython权限的问题
- python符号打印,bpython ,脚本tab自动补全
- python之生成随机数和字符串