牛骨文教育服务平台(让学习变的简单)
博文笔记

Python读取文件小结(csv,txt)

创建时间:2016-07-04 投稿人: 浏览次数:8704

搞了半天终于把Python读取文件的方式搞定了,这里简单说下


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


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。