Problem 5.2

Skip lines in a file

Write a program skip.py to print the contents of a file after skipping the first few lines.

The program takes an optional flag -n to indicate the number of lines to skip, which is considered as 5 when not specified.

The program takes a filename as argument and prints the contents of this file after skipping the number of lines specified by -n.

$ python skip.py files/ten.txt
6
7
8
9
10

$ python skip.py -n 8 files/ten.txt
9
10

Hint: Use argparse module.

Solution

import argparse

p = argparse.ArgumentParser()
p.add_argument("-n", type=int, default=5, help="number of lines to skip")
p.add_argument("filename", help="name of the file to consider")
args = p.parse_args()

lines = open(args.filename).readlines()

for line in lines[args.n:]:
    print(line, end="")