1+ #!/usr/bin/env python3
2+
3+ import sys
4+ import os
5+
6+ def count_file (file , options ):
7+ try :
8+ with open (file , 'r' , encoding = 'utf-8' ) as f :
9+ data = f .read ()
10+
11+ lines = data .count ('\n ' ) + 1
12+ words = len (data .split ())
13+ bytes_count = len (data .encode ('utf-8' ))
14+
15+ results = []
16+ if options ['lines' ] or not any (options .values ()):
17+ results .append (lines )
18+ if options ['words' ] or not any (options .values ()):
19+ results .append (words )
20+ if options ['bytes' ] or not any (options .values ()):
21+ results .append (bytes_count )
22+
23+ print (f"{ '\t ' .join (map (str , results ))} \t { file } " )
24+
25+ return lines , words , bytes_count
26+ except FileNotFoundError :
27+ print (f"wc: { file } : No such file or directory" , file = sys .stderr )
28+ sys .exit (1 )
29+
30+ def main ():
31+ args = sys .argv [1 :]
32+ options = {
33+ 'lines' : False ,
34+ 'words' : False ,
35+ 'bytes' : False ,
36+ }
37+
38+ files = []
39+
40+ for arg in args :
41+ if arg == '-l' :
42+ options ['lines' ] = True
43+ elif arg == '-w' :
44+ options ['words' ] = True
45+ elif arg == '-c' :
46+ options ['bytes' ] = True
47+ else :
48+ files .append (arg )
49+
50+ if not files :
51+ print ("Usage: wc [-l | -w | -c] <file>..." , file = sys .stderr )
52+ sys .exit (1 )
53+
54+ total_lines = 0
55+ total_words = 0
56+ total_bytes = 0
57+
58+ for file in files :
59+ lines , words , bytes_count = count_file (file , options )
60+ total_lines += lines
61+ total_words += words
62+ total_bytes += bytes_count
63+
64+ if len (files ) > 1 :
65+ total_results = []
66+ if options ['lines' ] or not any (options .values ()):
67+ total_results .append (total_lines )
68+ if options ['words' ] or not any (options .values ()):
69+ total_results .append (total_words )
70+ if options ['bytes' ] or not any (options .values ()):
71+ total_results .append (total_bytes )
72+
73+ print (f"{ '\t ' .join (map (str , total_results ))} \t total" )
74+
75+ if __name__ == "__main__" :
76+ main ()
0 commit comments