How to read a file in reverse order?

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

    I don't think this has been mentioned before, but using deque from collections and reverse works for me:

    from collections import deque
    
    fs = open("test.txt","rU")
    fr = deque(fs)
    fr.reverse()  # reverse in-place, returns None
    
    for li in fr:
       print li
    
    fs.close()
    

提交回复
热议问题