How to read a file in reverse order?

前端 未结 21 2565
礼貌的吻别
礼貌的吻别 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:46

    Always use with when working with files as it handles everything for you:

    with open('filename', 'r') as f:
        for line in reversed(f.readlines()):
            print line
    

    Or in Python 3:

    with open('filename', 'r') as f:
        for line in reversed(list(f.readlines())):
            print(line)
    

提交回复
热议问题