@@ -19,6 +19,27 @@ def count_file(file_path, count_lines=False, count_words=False, count_bytes=Fals
1919 bytes_count if count_bytes else None
2020 )
2121
22+
23+ def calculate_output (counts , flags , label ):
24+ """Helper to build consistent formatted output lines."""
25+ l_flag , w_flag , c_flag = flags
26+ count_strings = []
27+
28+ # If no flags are set, show all counts
29+ if not (l_flag or w_flag or c_flag ):
30+ lines , words , bytes_count = counts
31+ count_strings = [f"{ lines :>7} " , f"{ words :>7} " , f"{ bytes_count :>7} " ]
32+ else :
33+ if counts [0 ] is not None :
34+ count_strings .append (f"{ counts [0 ]:>7} " )
35+ if counts [1 ] is not None :
36+ count_strings .append (f"{ counts [1 ]:>7} " )
37+ if counts [2 ] is not None :
38+ count_strings .append (f"{ counts [2 ]:>7} " )
39+
40+ return f"{ ' ' .join (count_strings )} { label } "
41+
42+
2243def main ():
2344 parser = argparse .ArgumentParser (description = "count lines, words, and bytes like the wc command" )
2445 parser .add_argument ("-l" , action = "store_true" , help = "Count lines" )
@@ -35,38 +56,20 @@ def main():
3556
3657 for file_path in file_list :
3758 counts = count_file (file_path , args .l , args .w , args .c )
59+ total_lines += counts [0 ] or 0
60+ total_words += counts [1 ] or 0
61+ total_bytes += counts [2 ] or 0
3862
39- if not (args .l or args .w or args .c ):
40- lines , words , bytes_count = counts
41- print (f"{ lines :>7} { words :>7} { bytes_count :>7} { file_path } " )
42- total_lines += lines
43- total_words += words
44- total_bytes += bytes_count
45- else :
46- count_strings = []
47- if counts [0 ] is not None :
48- count_strings .append (f"{ counts [0 ]:>7} " )
49- total_lines += counts [0 ]
50- if counts [1 ] is not None :
51- count_strings .append (f"{ counts [1 ]:>7} " )
52- total_words += counts [1 ]
53- if counts [2 ] is not None :
54- count_strings .append (f"{ counts [2 ]:>7} " )
55- total_bytes += counts [2 ]
56- print (" " .join (count_strings ), file_path )
63+ print (calculate_output (counts , (args .l , args .w , args .c ), file_path ))
5764
5865 if len (file_list ) > 1 :
59- if not (args .l or args .w or args .c ):
60- print (f"{ total_lines :>7} { total_words :>7} { total_bytes :>7} total" )
61- else :
62- total_strings = []
63- if args .l :
64- total_strings .append (f"{ total_lines :>7} " )
65- if args .w :
66- total_strings .append (f"{ total_words :>7} " )
67- if args .c :
68- total_strings .append (f"{ total_bytes :>7} " )
69- print (" " .join (total_strings ), "total" )
66+ total_counts = (
67+ total_lines if args .l or not (args .l or args .w or args .c ) else None ,
68+ total_words if args .w or not (args .l or args .w or args .c ) else None ,
69+ total_bytes if args .c or not (args .l or args .w or args .c ) else None ,
70+ )
71+ print (calculate_output (total_counts , (args .l , args .w , args .c ), "total" ))
72+
7073
7174if __name__ == "__main__" :
7275 main ()
0 commit comments