zoukankan      html  css  js  c++  java
  • Python3实现从文件中读取指定行的方法

    from:http://www.jb51.net/article/66580.htm

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

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

    # 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='	'):
        """
        输入:文件名
        输出:数据集
        描述:从文件读入数据集
        """
        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:]:可以指定读取某几行的内容

  • 相关阅读:
    leetcode_question_67 Add Binary
    几种常用控件的使用方法
    JavaBean讲解 规范
    [置顶] JDK-CountDownLatch-实例、源码和模拟实现
    恋人分手后需要做的不是挽回而是二次吸引
    leetcode_question_70 Climbing Stairs
    偶然碰到的Win7 64位下CHM 的问题解决
    FTP中各文件目录的说明
    深入理解line-height与vertical-align(1)
    行内元素和块级元素
  • 原文地址:https://www.cnblogs.com/lindaxin/p/8073769.html
Copyright © 2011-2022 走看看