1- import sys
1+ import argparse
22
3- # Check if the user used a flag
4- if len (sys .argv ) > 1 and sys .argv [1 ] == "-n" :
3+ def print_file (filename , mode ):
4+ with open (filename , "r" ) as file :
5+ line_number = 1
56
6- # Start from the second argument because the first is "-n"
7- for filename in sys .argv [2 :]:
8-
9- with open (filename , "r" ) as file :
10-
11- line_number = 1
12-
13- for line in file :
7+ for line in file :
8+ if mode == "number_all" :
149 print (f"{ line_number } { line } " , end = "" )
1510 line_number += 1
1611
17-
18- elif len (sys .argv ) > 1 and sys .argv [1 ] == "-b" :
19-
20- # Start from the second argument because the first is "-b"
21- for filename in sys .argv [2 :]:
22-
23- with open (filename , "r" ) as file :
24-
25- line_number = 1
26-
27- for line in file :
28-
29- # Only number non-empty lines
12+ elif mode == "number_nonempty" :
3013 if line .strip () == "" :
3114 print (line , end = "" )
3215 else :
3316 print (f"{ line_number } { line } " , end = "" )
3417 line_number += 1
3518
19+ else :
20+ print (line , end = "" )
3621
37- else :
3822
39- # No flag, just print every file
40- for filename in sys .argv [1 :]:
23+ parser = argparse .ArgumentParser ()
24+ group = parser .add_mutually_exclusive_group ()
25+ group .add_argument ("-n" , action = "store_true" , help = "Number all lines" )
26+ group .add_argument ("-b" , action = "store_true" , help = "Number non-empty lines" )
27+ parser .add_argument ("filenames" , nargs = "+" )
28+
29+ args = parser .parse_args ()
30+
31+ if args .n :
32+ mode = "number_all"
33+ elif args .b :
34+ mode = "number_nonempty"
35+ else :
36+ mode = "none"
4137
42- with open ( filename , "r" ) as file :
43- print ( file . read (), end = "" )
38+ for filename in args . filenames :
39+ print_file ( filename , mode )
0 commit comments