File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import sys
2+ import argparse
3+ import os
4+
5+ parser = argparse .ArgumentParser (
6+ prog = "wc" ,
7+ description = "Word count" ,
8+ )
9+
10+ parser .add_argument ("-l" , action = "store_true" , help = "Count lines" )
11+ parser .add_argument ("-w" , action = "store_true" , help = "Count words" )
12+ parser .add_argument ("-c" , action = "store_true" , help = "Count bytes" )
13+ parser .add_argument ("paths" , nargs = "+" , help = "The files to process" )
14+
15+ args = parser .parse_args ()
16+
17+ totalLines = 0
18+ totalWords = 0
19+ totalBytes = 0
20+
21+ for path in args .paths :
22+ try :
23+ with open (path , "rb" ) as f :
24+ buffer = f .read ()
25+ content = buffer .decode ("utf-8" ) #, errors="ignore"
26+
27+ lines = len (content .split ("\n " )) - 1
28+ wordCount = len (content .strip ().split ())
29+ bytes = len (buffer )
30+
31+ totalLines += lines
32+ totalWords += wordCount
33+ totalBytes += bytes
34+
35+ if args .l :
36+ print (f"{ lines } { path } " )
37+ elif args .w :
38+ print (f"{ wordCount } { path } " )
39+ elif args .c :
40+ print (f"{ bytes } { path } " )
41+ else :
42+ print (f"{ lines } { wordCount } { bytes } { path } " )
43+ except Exception as e :
44+ print (f"Error reading { path } : { e } " )
45+
46+ if len (args .paths ) > 1 :
47+ if args .l :
48+ print (f"{ totalLines } total" )
49+ elif args .w :
50+ print (f"{ totalWords } total" )
51+ elif args .c :
52+ print (f"{ totalBytes } total" )
53+ else :
54+ print (f"{ totalLines } { totalWords } { totalBytes } total" )
You can’t perform that action at this time.
0 commit comments