88parser .add_argument ("-c" , dest = "chars" , action = "store_true" , help = "count the number of characters" )
99args = parser .parse_args ()
1010
11+ def output (line_count ,word_count ,char_count ,filename ,args ):
12+ if not (args .lines or args .words or args .chars ):
13+ return f"{ line_count } \t { word_count } \t { char_count } \t { filename } "
14+ output = []
15+ if args .lines :
16+ output .append (str (line_count ))
17+ if args .words :
18+ output .append (str (word_count ))
19+ if args .chars :
20+ output .append (str (char_count ))
21+ output .append (filename )
22+ return "\t " .join (output )
23+
24+ def count_file (path ):
25+ with open (path ) as f :
26+ text = f .read ()
27+ return (
28+ len (text .splitlines ()),
29+ len (text .split ()),
30+ len (text ),
31+ )
32+
1133if os .path .isdir (args .file ):
1234 files = os .listdir (args .file )
1335 for f in files :
1436 path = os .path .join (args .file , f )
1537 if os .path .isfile (path ):
16- with open (path , "r" ) as file_obj :
17- text = file_obj .read ()
18- line_count = len (text .splitlines ())
19- word_count = len (text .split ())
20- char_count = len (text )
21-
22- if not (args .lines or args .words or args .chars ):
23- print (f"{ line_count } \t { word_count } \t { char_count } \t { path } " )
24- continue
25- output = []
26- if args .lines :
27- output .append (str (line_count ))
28- if args .words :
29- output .append (str (word_count ))
30- if args .chars :
31- output .append (str (char_count ))
32- output .append (path )
33- print ("\t " .join (output ))
38+ line_count , word_count , char_count = count_file (path )
39+ print (output (line_count , word_count , char_count , path , args ))
3440else :
35-
36- with open (args .file , "r" ) as f :
37- text = f .read ()
38- line_count = len (text .splitlines ())
39- word_count = len (text .split ())
40- char_count = len (text )
41- if not (args .lines or args .words or args .chars ):
42- print (f"{ line_count } \t { word_count } \t { char_count } \t { args .file } " )
43- else :
44- output = []
45- if args .lines :
46- output .append (str (line_count ))
47- if args .words :
48- output .append (str (word_count ))
49- if args .chars :
50- output .append (str (char_count ))
51- output .append (args .file )
52- print ("\t " .join (output ))
53-
54-
55-
56-
57-
58-
59-
60-
61-
62-
63-
64-
65-
66-
41+ line_count , word_count , char_count = count_file (args .file )
42+ print (output (line_count , word_count , char_count , args .file , args ))
0 commit comments