利用python讀取檔案(針對大檔案和小檔案兩種)的首行(第一行)和末行(最後一行)。指令碼借鑑了前人的兩種處理思路(在下面的指令碼中有注釋說明引用出處),並修正了原先兩種處理方法中如果檔案末尾含有多個空行而返回空行的問題。
指令碼內容可以從github上獲取:
指令碼內容如下:
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""created by pycharm.
file: linuxbashshellscriptforops:getfilelastline.py
user: guodong
create date: 2016/9/1
create time: 11:05
"""import os
# refer:
def get_last_line(inputfile):
filesize = os.path.getsize(inputfile)
blocksize = 1024
dat_file = open(inputfile, 'rb')
last_line = ""
if filesize > blocksize:
maxseekpoint = (filesize // blocksize)
dat_file.seek((maxseekpoint - 1) * blocksize)
elif filesize:
# maxseekpoint = blocksize % filesize
dat_file.seek(0, 0)
lines = dat_file.readlines()
if lines:
last_line = lines[-1].strip()
# print "last line : ", last_line
dat_file.close()
return last_line
# refer:
def print_first_last_line(inputfile):
filesize = os.path.getsize(inputfile)
blocksize = 1024
dat_file = open(inputfile, 'rb')
headers = dat_file.readline().strip()
if filesize > blocksize:
maxseekpoint = (filesize // blocksize)
dat_file.seek(maxseekpoint * blocksize)
elif filesize:
maxseekpoint = blocksize % filesize
dat_file.seek(maxseekpoint)
lines = dat_file.readlines()
if lines:
last_line = lines[-1].strip()
# print "first line : ", headers
# print "last line : ", last_line
return headers, last_line
# my implementation
def get_file_last_line(inputfile):
filesize = os.path.getsize(inputfile)
blocksize = 1024
with open(inputfile, 'rb') as f:
last_line = ""
if filesize > blocksize:
maxseekpoint = (filesize // blocksize)
f.seek((maxseekpoint - 1) * blocksize)
elif filesize:
f.seek(0, 0)
lines = f.readlines()
if lines:
lineno = 1
while last_line == "":
last_line = lines[-lineno].strip()
lineno += 1
return last_line
# test purpose
# print get_last_line(os.path.abspath(__file__))
# print print_first_last_line(os.path.abspath(__file__))
# print get_file_last_line(os.path.abspath(__file__))
--end-- python讀取檔案最後一行
處理檔案時,乙個常見的需求就是讀取檔案的最後一行。那麼這個需求用python怎麼實現呢?乙個樸素的想法如下 with open a.log r as fp lines fp.readlines last line lines 1 即使不考慮異常處理的問題,這個 也不完美,因為如果檔案很大,lines...
python讀取檔案最後一行
處理檔案時,乙個常見的需求就是讀取檔案的最後一行。那麼這個需求用python怎麼實現呢?乙個樸素的想法如下 with open a.log r as fp lines fp.readlines last line lines 1 即使不考慮異常處理的問題,這個 也不完美,因為如果檔案很大,lines...
讀取檔案的最後一行
def get last line for small file fname with open fname,r encoding utf 8 as f 開啟檔案 lines f.readlines 讀取所有行 first line lines 0 取第一行 last line lines 1 取最...