您当前的位置:首页 > 计算机 > 编程开发 > Python

python篇---读取文件最后一行和从文件最后一行往上读取

时间:11-24来源:作者:点击数:
CDSY,CDSY.XYZ

python篇---读取文件最后一行和从文件最后一行往上读取

1、读取文件最后一行

三种方法

#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
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
                print(last_line)
        # return last_line


# Test purpose
# print(get_last_line("33011529001320014322.txt"))
# print(print_first_last_line("33011529001320014322.txt"))
print(get_file_last_line("33011529001320014322.txt"))

2、从文件最后一行往上读取

#!/usr/bin/env python
# -*-mode: python; coding: iso-8859-1 -*-
#
# Copyright (c) Peter Astrand <astrand@cendio.se>

import os


class BackwardsReader():
    """Read a file line by line, backwards"""
    BLKSIZE = 4096

    def __init__(self, file):
        self.file = file
        self.buf = ""
        self.file.seek(-1, 2)
        self.trailing_newline = 0
        lastchar = self.file.read(1)
        if lastchar == "\n":
            self.trailing_newline = 1
            self.file.seek(-1, 2)

    def readline(self):
        while 1:
            newline_pos = str.rfind(self.buf, "\n")
            print(newline_pos)
            pos = self.file.tell()
            if newline_pos != -1:
                # Found a newline
                line = self.buf[newline_pos+1:]
                self.buf = self.buf[:newline_pos]
                if pos != 0 or newline_pos != 0 or self.trailing_newline:
                    line += "\n"
                return line
            else:
                if pos == 0:
                    # Start-of-file
                    return ""
                else:
                    # Need to fill buffer
                    toread = min(self.BLKSIZE, pos)
                    self.file.seek(-toread, 1)
                    self.buf = self.file.read(toread).decode('UTF-8') + self.buf
                    self.file.seek(-toread, 1)
                    if pos - toread == 0:
                        self.buf = "\n" + self.buf


if __name__ == "__main__":
    br = BackwardsReader(open('33011529001320014322.txt', "rb"))
    # fixme:可修改数值21达到从末尾网上读取多行的需求
    for i in range(21):
        print(br.readline())
CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐