python文件IO---读取指定行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Blood_Seeker/article/details/81519413
# Python的标准库linecache模块非常适合这个任务
import linecache
the_line = linecache.getline( 'd:/FreakOut.cpp' , 222)
print (the_line)
# linecache读取并缓存文件中所有的文本,
# 若文件很大,而只读一行,则效率低下。
# 可显示使用循环, 注意enumerate从0开始计数,而line_number从1开始
def getline(the_file_path, line_number):
   if line_number < 1:
     return ''
   for cur_line_number, line in enumerate(open(the_file_path, 'rU' )):
     if cur_line_number == line_number-1:
       return line
   return ''
the_line = linecache.getline( 'd:/FreakOut.cpp' , 222)
print (the_line)
 
另一种方法:
def loadDataSet(fileName, splitChar= '\t' ):
     "" "
     输入:文件名
     输出:数据集
     描述:从文件读入数据集
     "" "
     dataSet = []
     with open(fileName) as fr:
         for line in fr.readlines()[6:]:
             curline = line.strip().split(splitChar)#字符串方法strip():返回去除两侧(不包括)内部空格的字符串;字符串方法spilt:按照制定的字符将字符串分割成序列
             fltline = list(map( float , curline))#list函数将其他类型的序列转换成字符串;map函数将序列curline中的每个元素都转为浮点型
             dataSet.append(fltline)
     return dataSet

猜你喜欢

转载自blog.csdn.net/Blood_Seeker/article/details/81519413
今日推荐