欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python如何獲取文件指定行的內(nèi)容

 更新時(shí)間:2020年05月27日 15:33:04   作者:Python  
在本篇文章里小編給大家分享的是關(guān)于Python獲取文件指定行的內(nèi)容的方法,有需要的朋友們可以學(xué)習(xí)下。

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ù)是文件名,第二個(gè)參數(shù)是行編號(hào)。如果文件名不能直接找到的話,會(huì)從 sys.path 里找。

如果請(qǐng)求的行數(shù)超過文件行數(shù),函數(shù)不會(huì)報(bào)錯(cuò),而是返回''空字符串。

如果文件不存在,函數(shù)也不會(huì)報(bào)錯(cuò),也返回''空字符串。

# Python的標(biāo)準(zhǔn)庫linecache模塊非常適合這個(gè)任務(wù)
import linecache
the_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 ''

方法擴(kuò)展:

'''
遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:857662006 
尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書!
'''
# Python的標(biāo)準(zhǔn)庫linecache模塊非常適合這個(gè)任務(wù)
import linecache
the_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)

到此這篇關(guān)于Python如何獲取文件指定行的內(nèi)容的文章就介紹到這了,更多相關(guān)Python獲取文件指定行的內(nèi)容的方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論