相关疑难解决方法(0)

使用Python获取文件的最后n行,类似于tail

我正在为Web应用程序编写一个日志文件查看器,为此我想通过日志文件的行分页.文件中的项目是基于行的,底部是最新项目.

所以我需要一种tail()方法,可以n从底部读取行并支持偏移量.我想出的是这样的:

def tail(f, n, offset=0):
    """Reads a n lines from f with an offset of offset lines."""
    avg_line_length = 74
    to_read = n + offset
    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
            # to step back, go to the beginning instead
            f.seek(0)
        pos = f.tell()
        lines = f.read().splitlines()
        if len(lines) >= to_read or pos == 0:
            return lines[-to_read:offset and -offset or None]
        avg_line_length …
Run Code Online (Sandbox Code Playgroud)

python file-io file tail logfiles

174
推荐指数
10
解决办法
14万
查看次数

使用python以相反的顺序读取文件

如何使用python以相反的顺序读取文件?我想从最后一行到第一行读取一个文件.

python reverse file

112
推荐指数
7
解决办法
12万
查看次数

在python中读取文件的最后一行

我有两个要求.

第一个要求 - 我想读取文件的最后一行,并将最后一个值赋给python中的变量.

第二要求 -

这是我的示例文件.

<serviceNameame="demo" wsdlUrl="demo.wsdl" serviceName="demo"/>
<context:property-placeholder location="filename.txt"/>
Run Code Online (Sandbox Code Playgroud)

从这个文件我想读取内容,即filename.txt将在之后<context:property-placeholder location= ..并希望将该值赋给python中的变量.

python python-2.7 python-3.x python-requests

3
推荐指数
5
解决办法
8347
查看次数