python文件IO---讀取指定行


# 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM