首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何以逆序读取文件?

如何以逆序读取文件?
EN

Stack Overflow用户
提问于 2010-02-20 18:09:27
回答 18查看 174.7K关注 0票数 148

如何使用python逆序读取文件?我想把文件从最后一行读到第一行。

EN

回答 18

Stack Overflow用户

回答已采纳

发布于 2010-02-20 18:10:52

代码语言:javascript
复制
for line in reversed(open("filename").readlines()):
    print line.rstrip()

在Python 3中:

代码语言:javascript
复制
for line in reversed(list(open("filename"))):
    print(line.rstrip())
票数 86
EN

Stack Overflow用户

发布于 2014-05-14 13:09:51

一种写成生成器的正确有效的答案。

代码语言:javascript
复制
import os

def reverse_readline(filename, buf_size=8192):
    """A generator that returns the lines of a file in reverse order"""
    with open(filename) as fh:
        segment = None
        offset = 0
        fh.seek(0, os.SEEK_END)
        file_size = remaining_size = fh.tell()
        while remaining_size > 0:
            offset = min(file_size, offset + buf_size)
            fh.seek(file_size - offset)
            buffer = fh.read(min(remaining_size, buf_size))
            remaining_size -= buf_size
            lines = buffer.split('\n')
            # The first line of the buffer is probably not a complete line so
            # we'll save it and append it to the last line of the next buffer
            # we read
            if segment is not None:
                # If the previous chunk starts right from the beginning of line
                # do not concat the segment to the last line of new chunk.
                # Instead, yield the segment first 
                if buffer[-1] != '\n':
                    lines[-1] += segment
                else:
                    yield segment
            segment = lines[0]
            for index in range(len(lines) - 1, 0, -1):
                if lines[index]:
                    yield lines[index]
        # Don't yield None if the file was empty
        if segment is not None:
            yield segment
票数 172
EN

Stack Overflow用户

发布于 2017-01-02 03:05:12

您也可以使用python模块file_read_backwards

安装后,通过pip install file_read_backwards (v1.2.1),您可以通过以下方式以内存高效的方式向后读取整个文件(逐行):

代码语言:javascript
复制
#!/usr/bin/env python2.7

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/path/to/file", encoding="utf-8") as frb:
    for l in frb:
         print l

它支持"utf-8“、"latin-1”和"ascii“编码。

还提供了对python3的支持。有关更多文档,请访问http://file-read-backwards.readthedocs.io/en/latest/readme.html

票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2301789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档