Copy the last three lines of a text file in python?

前端 未结 5 1775
故里飘歌
故里飘歌 2020-12-17 03:40

I\'m new to python and the way it handles variables and arrays of variables in lists is quite alien to me. I would normally read a text file into a vector and then copy the

5条回答
  •  天涯浪人
    2020-12-17 04:09

    To get the last three lines of a file efficiently, use deque:

    from collections import deque
    
    with open('somefile') as fin:
        last3 = deque(fin, 3)
    

    This saves reading the whole file into memory to slice off what you didn't actually want.

    To reflect your comment - your complete code would be:

    from collections import deque
    
    with open('somefile') as fin, open('outputfile', 'w') as fout:
        fout.writelines(deque(fin, 3))
    

提交回复
热议问题