python读写文件操作

在这里插入图片描述
找了半天错误,这里文件要读2次,记录下。或者:

import numpy as np
filepath='/home/huanglong/tensorflow/Machine-learning-in-action-master/k-Nearest Neighbor/datingTestSet2.txt'
with open(filepath,'r') as fr:
    numberOfLines = len(fr.readlines())         #get the number of lines in the file
    returnMat = np.zeros((numberOfLines,3))
    print returnMat,numberOfLines
    classLabelVector=[]
    index=0
with open(filepath,'r') as fr:
    for line in fr.readlines():
        listFromLine = line.strip().split('\t')
        returnMat[index,:]=listFromLine[0:3]
        index += 1
        print listFromLine

猜你喜欢

转载自blog.csdn.net/weixin_38632246/article/details/87192787