1+ #!/usr/bin/env python3
2+
3+ import argparse
4+ import sys
5+ import os
6+
7+ parser = argparse .ArgumentParser (
8+ prog = 'wc' ,
9+ description = 'Displays number of words, lines, and bytes in a file'
10+ )
11+
12+ parser .add_argument ('-l' , '--lines' , action = 'store_true' , help = 'counts number of lines' )
13+ parser .add_argument ('-w' , '--words' , action = 'store_true' , help = 'counts sequence of characters' )
14+ parser .add_argument ('-c' , '--bytes' , action = 'store_true' , help = 'counts raw size of a file in bytes' )
15+ parser .add_argument ('files' , nargs = '+' , help = 'Files to read' )
16+
17+ args = parser .parse_args ()
18+
19+ if not args .files :
20+ print (f"wc: missing file to read" )
21+ sys .exit (1 )
22+
23+ total_lines , total_words , total_bytes = 0 , 0 , 0
24+
25+ for file in args .files :
26+ try :
27+ with open (file , 'r' ) as f :
28+ content = f .read ()
29+
30+ line_count = content .count ('\n ' )
31+ word_count = len (content .split ())
32+ byte_count = os .path .getsize (file )
33+
34+ total_lines += line_count
35+ total_words += word_count
36+ total_bytes += byte_count
37+
38+ show_all = not (args .lines or args .words or args .bytes )
39+
40+ output = ""
41+ if args .lines or show_all :
42+ output += f"{ line_count :>7} "
43+ if args .words or show_all :
44+ output += f"{ word_count :>7} "
45+ if args .bytes or show_all :
46+ output += f"{ byte_count :>7} "
47+
48+ print (f"{ output } { file } " )
49+
50+ except FileNotFoundError :
51+ print (f"wc: { args .path } : No such file or directory." , file = sys .stderr )
52+
53+
54+ if len (args .files ) > 1 :
55+ total = ""
56+ if args .lines or show_all :
57+ total += f"{ total_lines :>7} "
58+ if args .words or show_all :
59+ total += f"{ total_words :>7} "
60+ if args .bytes or show_all :
61+ total += f"{ total_bytes :>7} "
62+
63+ print (f"{ total } total" )
0 commit comments