Python实现从文件中读取指定行的方法

admin 2018年6月12日14:54:01Python评论1,653 次浏览阅读模式

这篇文章主要介绍了Python3实现从文件中读取指定行的方法,涉及Python中linecache模块操作文件的使用技巧,需要的朋友可以参考下

本文实例讲述了Python3实现从文件中读取指定行的方法。分享给大家供大家参考。具体实现方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 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)

 还有一种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
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

 改变语句for line in fr.readlines()[6:]:可以指定读取某几行的内容

相关文章
weinxin
我的微信
微信扫一扫
admin
  • 本文由 发表于 2018年6月12日14:54:01
  • 转载请务必保留本文链接:https://anyun.org/a/jishuguanzhu/bianchengchalou/python/2018/0612/9449.html

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: