Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip last 5 line in a file using python

Tags:

python

I wanted to remove last few lines in a file using python. The file is huge in size,so to remove first few line I'm using the following code

import sys
with open(sys.argv[1],"rb") as f:
    for _ in range(6):#skip first 6 lines
        next(f)
    for line in f:
        print line
like image 946
jOSe Avatar asked Mar 14 '23 22:03

jOSe


1 Answers

Here's a generalized generator for truncating any iterable:

from collections import deque

def truncate(iterable, num):
    buffer = deque(maxlen=num)
    iterator = iter(iterable)

    # Initialize buffer
    for n in range(num):
        buffer.append(next(iterator))

    for item in iterator:
        yield buffer.popleft()
        buffer.append(item)

truncated_range20 = truncate(range(20), 5)

print(list(truncated_range20))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Using truncate, you can do this:

from __future__ import print_function

import sys

from itertools import islice


filepath = sys.argv[1]

with open(filepath, 'rb') as f:
    for line in truncate(islice(f, 6, None), 5):
        print(line, end='')
like image 85
Cyphase Avatar answered Mar 24 '23 07:03

Cyphase