新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:怎么通過Python獲取文件指定行的內(nèi)容?
linecache, 可以用它方便地獲取某一文件某一行的內(nèi)容。而且它也被 traceback 模塊用來獲取相關(guān)源碼信息來展示。

用法很簡單:
>>> import linecache
>>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\n'linecache.getline 第一參數(shù)是文件名,第二個參數(shù)是行編號。如果文件名不能直接找到的話,會從 sys.path 里找。
如果請求的行數(shù)超過文件行數(shù),函數(shù)不會報錯,而是返回''空字符串。
如果文件不存在,函數(shù)也不會報錯,也返回''空字符串。
# python的標(biāo)準(zhǔn)庫linecache模塊非常適合這個任務(wù)
import linecache
the_line = linecache.getline('d:/FreakOut.cpp', 222)
print (the_line)
# linecache讀取并緩存文件中所有的文本,
# 若文件很大,而只讀一行,則效率低下。
# 可顯示使用循環(huán), 注意enumerate從0開始計數(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) 網(wǎng)站標(biāo)題:創(chuàng)新互聯(lián)Python教程:怎么通過Python獲取文件指定行的內(nèi)容?
本文網(wǎng)址:http://m.fisionsoft.com.cn/article/dhhipei.html


咨詢
建站咨詢
