Python3實現從文件中讀取指定行的方法
來源:懂視網
責編:小采
時間:2020-11-27 14:41:22
Python3實現從文件中讀取指定行的方法
Python3實現從文件中讀取指定行的方法:本文實例講述了Python3實現從文件中讀取指定行的方法。分享給大家供大家參考。具體實現方法如下: # Python的標準庫linecache模塊非常適合這個任務 import linecache the_line = linecache.getline('d:/FreakOut.cpp', 222
導讀Python3實現從文件中讀取指定行的方法:本文實例講述了Python3實現從文件中讀取指定行的方法。分享給大家供大家參考。具體實現方法如下: # Python的標準庫linecache模塊非常適合這個任務 import linecache the_line = linecache.getline('d:/FreakOut.cpp', 222

本文實例講述了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)
希望本文所述對大家的Python程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
Python3實現從文件中讀取指定行的方法
Python3實現從文件中讀取指定行的方法:本文實例講述了Python3實現從文件中讀取指定行的方法。分享給大家供大家參考。具體實現方法如下: # Python的標準庫linecache模塊非常適合這個任務 import linecache the_line = linecache.getline('d:/FreakOut.cpp', 222