python讀取檔案指定行內容例項講解
阿新 • • 發佈:2020-03-02
python讀取檔案指定行內容
import linecache text=linecache.getline(r'C:\Users\Administrator\Desktop\SourceCodeofMongoRedis\chapter_5\generate_string.py',10) 第十行內容為# info = '''1000001 王小小'''
例項擴充套件:
本文例項講述了Python3實現從檔案中讀取指定行的方法。分享給大家供大家參考。具體實現方法如下:
''' 遇到問題沒人解答?小編建立了一個Python學習交流QQ群:857662006 尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視訊學習教程和PDF電子書! ''' # 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)
還有一種方法
''' 遇到問題沒人解答?小編建立了一個Python學習交流QQ群:857662006 尋找有志同道合的小夥伴,互幫互助,群裡還有不錯的視訊學習教程和PDF電子書! ''' 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讀取檔案指定行內容內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!