How to read a file in reverse order?

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

    I had to do this some time ago and used the below code. It pipes to the shell. I am afraid i do not have the complete script anymore. If you are on a unixish operating system, you can use "tac", however on e.g. Mac OSX tac command does not work, use tail -r. The below code snippet tests for which platform you're on, and adjusts the command accordingly

    # We need a command to reverse the line order of the file. On Linux this
    # is 'tac', on OSX it is 'tail -r'
    # 'tac' is not supported on osx, 'tail -r' is not supported on linux.
    
    if sys.platform == "darwin":
        command += "|tail -r"
    elif sys.platform == "linux2":
        command += "|tac"
    else:
        raise EnvironmentError('Platform %s not supported' % sys.platform)
    

提交回复
热议问题