假设文本文件中保存的是形如矩阵的数据,但由于文本文件的格式所限,打开文件后按行读取到的类型是字符串,不方便后续按数值处理,所以需要进行类型转换。参考网查并在Python2.7.5中调试后,总结为以下两种方式:
(1)已知矩阵列数但行数未知(读取文件文件时获取行数)时:
from numpy import *
from FileDialog import *
import tkFileDialog
def txt2RealMat(): #define a function to get the real array
try:
filename=tkFileDialog.askopenfilename(initialdir='D:/') # the default path of .txt file
except ValueError:
pass
with open(filename,'r') as fr:
initDataRow=len(fr.readlines()) # get the number of rows
initDataCol=5 # suppose the default number of columns is 5
dataMat=zeros((initDataRow,initDataCol),dtype=float)
tempRow=0