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
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='')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With