python讀取文件指定行內(nèi)容實(shí)例講解
python讀取文件指定行內(nèi)容
import linecachetext=linecache.getline(r’C:UsersAdministratorDesktopSourceCodeofMongoRedischapter_5generate_string.py’,10)第十行內(nèi)容為# info = ’’’1000001 王小小’’’
實(shí)例擴(kuò)展:
本文實(shí)例講述了Python3實(shí)現(xiàn)從文件中讀取指定行的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
’’’’’’# Python的標(biāo)準(zhǔn)庫linecache模塊非常適合這個(gè)任務(wù)import linecachethe_line = linecache.getline(’d:/FreakOut.cpp’, 222)print (the_line)# linecache讀取并緩存文件中所有的文本,# 若文件很大,而只讀一行,則效率低下。# 可顯示使用循環(huán), 注意enumerate從0開始計(jì)數(shù),而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’): ''' 輸入:文件名 輸出:數(shù)據(jù)集 描述:從文件讀入數(shù)據(jù)集 ''' dataSet = [] with open(fileName) as fr: for line in fr.readlines()[6:]: curline = line.strip().split(splitChar)#字符串方法strip():返回去除兩側(cè)(不包括)內(nèi)部空格的字符串;字符串方法spilt:按照制定的字符將字符串分割成序列 fltline = list(map(float, curline))#list函數(shù)將其他類型的序列轉(zhuǎn)換成字符串;map函數(shù)將序列curline中的每個(gè)元素都轉(zhuǎn)為浮點(diǎn)型 dataSet.append(fltline) return dataSet
改變語句for line in fr.readlines()[6:]:可以指定讀取某幾行的內(nèi)容
到此這篇關(guān)于python讀取文件指定行內(nèi)容實(shí)例講解的文章就介紹到這了,更多相關(guān)python讀取文件指定行內(nèi)容內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. jsp實(shí)現(xiàn)簡單用戶7天內(nèi)免登錄2. ASP.NET MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳3. xml文件的結(jié)構(gòu)解讀第1/2頁4. ASP.NET MVC實(shí)現(xiàn)登錄后跳轉(zhuǎn)到原界面5. 父div高度不能自適應(yīng)子div高度的解決方案6. 怎樣打開XML文件?xml文件如何打開?7. 讓 Asp 與 XML 交互8. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)9. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識(shí))10. PHP Session條件競爭超詳細(xì)講解
