前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python读取文件的最后一行(非空行)

Python读取文件的最后一行(非空行)

作者头像
py3study
发布2020-01-07 14:56:33
4.1K0
发布2020-01-07 14:56:33
举报
文章被收录于专栏:python3python3python3

利用Python读取文件(针对大文件和小文件两种)的首行(第一行)和末行(最后一行)。脚本借鉴了前人的两种处理思路(在下面的脚本中有注释说明引用出处),并修正了原先两种处理方法中如果文件末尾含有多个空行而返回空行的问题。

脚本内容可以从GitHub上获取:

https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/file/getFileLastLine.py

脚本内容如下:

#!/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: http://www.pythonclub.org/python-files/last-line
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: http://code.activestate.com/recipes/578095/
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--

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档