反序遍历文件

感觉挺好玩的, mark一下

import sys
def readReverse(fName, step):
    f = open(fName)
    f.seek(0, 2)
    lastPos = f.tell()
    
    while True:
        line = f.readline()
        currentPos = f.tell()
        i = 1
        # 负责后退
        while lastPos == currentPos:
            if len(line) == currentPos: //  第一行数据 
                yield line
                return 
            i += 0.5
            f.seek(max(int(-step*i), -currentPos), 1)  # 这里的只可以参考文件每行大小, 随便选这个值step 选长选小都会和下面的while
            line = f.readline()
            currentPos = f.tell()
        ## 负责前进
        while currentPos != lastPos: 
            line = f.readline()
            currentPos = f.tell()
        yield line
        lastPos -= len(line)
        f.seek(max(-step, -lastPos) - len(line), 1)  #  同上r
if __name__ == '__main__':
    if len(sys.argv) <= 1:
        sys.exit()
    f = open("reverse.txt", 'w')
    for each in readReverse(sys.argv[1]):  
        print each
        f.write(each)
    f.close()

你可能感兴趣的:(反序遍历文件)