成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python讀取文件指定行內(nèi)容實(shí)例講解

瀏覽:3日期:2022-08-04 18:39:56

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)庫(kù)linecache模塊非常適合這個(gè)任務(wù)import linecachethe_line = linecache.getline(’d:/FreakOut.cpp’, 222)print (the_line)# linecache讀取并緩存文件中所有的文本,# 若文件很大,而只讀一行,則效率低下。# 可顯示使用循環(huán), 注意enumerate從0開(kāi)始計(jì)數(shù),而line_number從1開(kāi)始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

改變語(yǔ)句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)!

標(biāo)簽: Python 編程
相關(guān)文章: