How to read a file in reverse order?

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

    Read the file line by line and then add it on a list in reverse order.

    Here is an example of code :

    reverse = []
    with open("file.txt", "r") as file:
        for line in file:
            line = line.strip()
             reverse[0:0] = line
    

提交回复
热议问题