How to read a file in reverse order?

前端 未结 21 2580
礼貌的吻别
礼貌的吻别 2020-11-22 04:51

How to read a file in reverse order using python? I want to read a file from last line to first line.

21条回答
  •  后悔当初
    2020-11-22 05:52

    You can also use python module file_read_backwards.

    After installing it, via pip install file_read_backwards (v1.2.1), you can read the entire file backwards (line-wise) in a memory efficient manner via:

    #!/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
    

    It supports "utf-8","latin-1", and "ascii" encodings.

    Support is also available for python3. Further documentation can be found at http://file-read-backwards.readthedocs.io/en/latest/readme.html

提交回复
热议问题