11import argparse
22import os
33
4+
5+ # Set up argument parser for wc command
46parser = argparse .ArgumentParser (prog = "wc" ,usage = "implement a simple wc in python" )
57parser .add_argument ("-l" ,action = "store_true" ,help = "count of lines" )
68parser .add_argument ("-w" ,action = "store_true" ,help = "count of words" )
1517total_words = 0
1618total_bytes = 0
1719
20+ # Function to print counts for a file or total
21+ def print_wc (lines , words , bytes_ , name ):
22+ # Print selected counts in formatted columns
23+ print (
24+ (f"{ lines :<5} " if args .l else "" ) +
25+ (f"{ words :<5} " if args .w else "" ) +
26+ (f"{ bytes_ :<5} " if args .c else "" ) +
27+ f"{ name :<20} "
28+ )
29+
30+ # Loop through all files
1831for file in paths :
1932 with open (file ,"r" ) as f :
33+ # Get file size in bytes
2034 bytes_count = os .path .getsize (file )
35+ # Read all lines
2136 lines = f .readlines ()
2237 lines_count = len (lines )
2338 for line in lines :
39+ # Count words in file
2440 words_count += len (line .split ())
41+
42+ # Update totals
2543 total_lines += lines_count
2644 total_bytes += bytes_count
2745 total_words += words_count
46+
47+ # If no flags provided, default to showing all counts
2848 if not (args .l or args .w or args .c ):
2949 args .l = True
3050 args .w = True
3151 args .c = True
32- print ((f"{ lines_count :<5} " if args .l else "" )+
33- (f"{ words_count :<5} " if args .w else "" )+
34- (f"{ bytes_count :<5} " if args .c else "" )+
35- f"{ file :<20} " )
36- words_count = 0
52+ # Print counts for this file
53+ print_wc (lines_count , words_count , bytes_count , file )
3754
55+ # If multiple files, print totals at the end
3856if len (paths )> 1 :
39- print ((f"{ total_lines :<5} " if args .l else "" )+
40- (f"{ total_words :<5} " if args .w else "" )+
41- (f"{ total_bytes :<5} " if args .c else "" )+
42- "total" )
57+ print_wc (total_lines , total_words , total_bytes , "total" )
58+
0 commit comments