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='\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:]:可以指定讀取某幾行的內容
