How to read a file in reverse order?

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

    you would need to first open your file in read format, save it to a variable, then open the second file in write format where you would write or append the variable using a the [::-1] slice, completely reversing the file. You can also use readlines() to make it into a list of lines, which you can manipulate

    def copy_and_reverse(filename, newfile):
        with open(filename) as file:
            text = file.read()
        with open(newfile, "w") as file2:
            file2.write(text[::-1])
    

提交回复
热议问题