相关疑难解决方法(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 2.5上选择模块的问题

我在Python 2.5中有一个监听beanstalk队列的应用程序.它在我测试的所有机器上都能正常工作,除了我新购买的MacBook Pro.

在那台计算机上,当我尝试运行它时,我收到此错误:

Traceback (most recent call last):
  File "jobs.py", line 181, in <module>
    Jobs().start()
  File "jobs.py", line 154, in start
    self.jobQueue = Queue()
  File "src/utils/queue.py", line 16, in __init__
    self.connection = serverconn.ServerConn(self.server, self.port)
  File "src/beanstalk/serverconn.py", line 25, in __init__
    self.poller = select.poll()
AttributeError: 'module' object has no attribute 'poll'
Run Code Online (Sandbox Code Playgroud)

serverconn.py具有以下导入:

import socket, select
Run Code Online (Sandbox Code Playgroud)

当我尝试从命令行运行它时,它也会失败:

Python 2.5.1 (r251:54863, Jul 23 2008, 11:00:16) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information. …
Run Code Online (Sandbox Code Playgroud)

python macos beanstalkd

3
推荐指数
1
解决办法
3653
查看次数

从 CSV 输入 Python 中查找最后一行

我没有真正找到与我的问题相关的示例,因为我不了解 Pandas,所以我将其发布在这里。如果不清楚或已经得到答复,请告诉我。

我有一个 CSV 输入,我像这样导入

def import_csv(csvfilename):
    data = []
    with open(csvfilename, "r", encoding="utf-8", errors="ignore") as scraped:
        reader = csv.reader(scraped, delimiter=',')
        row_index = 0
        for row in reader:
            if row:  # avoid blank lines
                row_index += 1
                columns = [str(row_index), row[0], row[1], row[2]]
                data.append(columns)

    return data
Run Code Online (Sandbox Code Playgroud)

我用 input_rows 索引行(可能有更好的方法吗?)

输入示例:

[['1',
  '[FirstValue]',
  'FirstText',
  'AB'],

 [...]

 ['12',
  "['LastValue']",
  "LastText",
  'YZ']]
Run Code Online (Sandbox Code Playgroud)

我正在寻找此输入列表的最后一行。有没有一种简单的方法可以做到这一点,而无需迭代所有行?

谢谢 !

python

3
推荐指数
1
解决办法
4万
查看次数

标签 统计

python ×3

beanstalkd ×1

file ×1

file-io ×1

logfiles ×1

macos ×1

tail ×1