相关疑难解决方法(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万
查看次数

对大型XML文件使用Python Iterparse

我需要在Python中编写一个解析器,它可以在没有太多内存(仅2 GB)的计算机上处​​理一些非常大的文件(> 2 GB).我想在lxml中使用iterparse来做到这一点.

我的文件格式为:

<item>
  <title>Item 1</title>
  <desc>Description 1</desc>
</item>
<item>
  <title>Item 2</title>
  <desc>Description 2</desc>
</item>
Run Code Online (Sandbox Code Playgroud)

到目前为止我的解决方案是:

from lxml import etree

context = etree.iterparse( MYFILE, tag='item' )

for event, elem in context :
      print elem.xpath( 'description/text( )' )

del context
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个解决方案仍然占用了大量的内存.我认为问题在于,在处理每个"ITEM"后,我需要做一些事情来清理空的孩子.在处理我的数据到正确清理之后,有人可以提供一些建议吗?

python xml lxml elementtree large-files

36
推荐指数
2
解决办法
3万
查看次数

标签 统计

python ×2

elementtree ×1

file ×1

file-io ×1

large-files ×1

logfiles ×1

lxml ×1

tail ×1

xml ×1