66 prog = "a simple version of wc. Takes in one or more files." ,
77 description = "ls command line tool which can accept -l -w -c cflags" )
88
9- parser .add_argument ("-l" , action = "store_true" , help = "show line count" )
10- parser .add_argument ("-w" , action = "store_true" , help = "show word count" )
11- parser .add_argument ("-c" , action = "store_true" , help = "show byte count" )
9+ parser .add_argument ("-l" , action = "store_true" , help = "show line count" , default = "l" )
10+ parser .add_argument ("-w" , action = "store_true" , help = "show word count" , default = 'w' )
11+ parser .add_argument ("-c" , action = "store_true" , help = "show byte count" , default = "c" )
1212
1313parser .add_argument ("paths" , nargs = "*" , help = "file(s) for which to show data" )
1414
15- args = parser .parse_args ()
15+ args = parser .parse_args ()
16+
17+ totals = {"l" : 0 , "w" : 0 , "c" : 0 }
18+
19+ file_count = 0
20+
21+ for path in args .paths :
22+ try :
23+ if (os .path .isdir (path )):
24+ print (f"wc: { path } : read: Is a directory" )
25+ except :
26+ print (f"wc: { path } open: No such file or directory" , file = sys .stderr )
27+ file_count += 1
28+ continue
29+
30+ if (os .path .isfile (path )):
31+ file_count += 1
32+ output_str = ""
33+
34+ with open (path , "r" , encoding = "utf-8" ) as file :
35+ lines = file .readlines ()
36+
37+ if (args .l ):
38+ if (len (lines ) > 0 and lines [- 1 ] == "" ):
39+ lines .pop ()
40+
41+ line_count = len (lines )
42+ totals ["l" ] += line_count
43+ output_str += f"\t { line_count } "
44+
45+ if (args .w ):
46+ word_count = 0
47+ for line in lines :
48+ # python string.split splits on any white space
49+ word_count += len (line .split ())
50+ totals ["w" ] += word_count
51+ output_str += f"\t { word_count } "
52+
53+ if (args .c ):
54+ bytes = os .path .getsize (path )
55+ totals ["c" ] += bytes
56+ output_str += f"\t { bytes } "
57+
58+ output_str += f" { path } "
59+ print (output_str )
60+
61+ if (file_count > 1 ):
62+ res = {key : val for key , val in totals .items ()
63+ if val != 0 }
64+ total_str = ""
65+ for v in res .values ():
66+ total_str += f"\t { v } "
67+
68+ total_str += " total"
69+ print (total_str )
70+
71+
72+
73+
74+
0 commit comments