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

Python如何獲取文件指定行的內容

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

linecache, 可以用它方便地獲取某一文件某一行的內容。而且它也被 traceback 模塊用來獲取相關源碼信息來展示。

用法很簡單:

>>> 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的標準庫linecache模塊非常適合這個任務
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 ''

方法擴展:

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

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

相關文章

最新評論