python读取文件指定行内容实例讲解

发布时间:2020-10-07 00:45:23 作者:阿布gogo
来源:脚本之家 阅读:255

python读取文件指定行内容

import linecache
text=linecache.getline(r'C:\Users\Administrator\Desktop\SourceCodeofMongoRedis\chapter_5\generate_string.py',10)
第十行内容为# info = '''1000001 王小小'''

实例扩展:

本文实例讲述了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='\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:]:可以指定读取某几行的内容

到此这篇关于python读取文件指定行内容实例讲解的文章就介绍到这了,更多相关python读取文件指定行内容内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

推荐阅读:
  1. shell脚本按行读取文件内容的方法
  2. python按行读取文件并找出其中指定字符串

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 读取文件

上一篇:Python读写zip压缩文件的方法

下一篇:Tcp协议三次握手跟四次挥手

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》