如何通过Python实例演示读取文件特定行内容的方法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计341个文字,预计阅读时间需要2分钟。
Python读取文件指定行内容,不使用数数,直接输出:
pythonimport linecache
text=linecache.getline('C:/Users/Administrator/Desktop/SourceCodeofMongoRedis/chapter_5/generate_string.py', 10)print(text.strip())
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读取文件指定行内容内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
本文共计341个文字,预计阅读时间需要2分钟。
Python读取文件指定行内容,不使用数数,直接输出:
pythonimport linecache
text=linecache.getline('C:/Users/Administrator/Desktop/SourceCodeofMongoRedis/chapter_5/generate_string.py', 10)print(text.strip())
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读取文件指定行内容内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

