|
4 | 4 | count_lines = "-l" in sys.argv |
5 | 5 | count_words = "-w" in sys.argv |
6 | 6 | count_bytes = "-c" in sys.argv |
| 7 | + |
7 | 8 | filenames = [] |
8 | 9 |
|
9 | 10 | for argument in sys.argv[1:]: |
10 | 11 | if not argument.startswith("-"): |
11 | 12 | filenames.append(argument) |
12 | 13 |
|
13 | | -total_lines = 0 |
14 | | -total_words = 0 |
15 | | -total_bytes = 0 |
16 | | - |
17 | | -for filename in filenames: |
18 | | - file = open(filename) |
19 | | - |
20 | | - line_count = 0 |
21 | | - word_count = 0 |
22 | | - |
23 | | - for line in file: |
24 | | - line_count += 1 |
25 | | - word_count += len(line.split()) |
26 | | - byte_count = os.path.getsize(filename) |
27 | | - |
28 | | - total_lines += line_count |
29 | | - total_words += word_count |
30 | | - total_bytes += byte_count |
31 | | - |
| 14 | +def format_counts(line_count, word_count, byte_count): |
32 | 15 | output = [] |
33 | 16 |
|
34 | 17 | if count_lines: |
|
40 | 23 | if count_bytes: |
41 | 24 | output.append(byte_count) |
42 | 25 |
|
43 | | - |
44 | 26 | if not count_lines and not count_words and not count_bytes: |
45 | 27 | output.append(line_count) |
46 | 28 | output.append(word_count) |
|
51 | 33 | for number in output: |
52 | 34 | formatted_output.append(f"{number:3}") |
53 | 35 |
|
54 | | - print(" ".join(formatted_output), filename) |
| 36 | + return " ".join(formatted_output) |
55 | 37 |
|
56 | | -if len(filenames) > 1: |
57 | | - total_output = [] |
| 38 | +total_lines = 0 |
| 39 | +total_words = 0 |
| 40 | +total_bytes = 0 |
58 | 41 |
|
59 | | - if count_lines: |
60 | | - total_output.append(total_lines) |
| 42 | +for filename in filenames: |
| 43 | + file = open(filename) |
61 | 44 |
|
62 | | - if count_words: |
63 | | - total_output.append(total_words) |
| 45 | + line_count = 0 |
| 46 | + word_count = 0 |
64 | 47 |
|
65 | | - if count_bytes: |
66 | | - total_output.append(total_bytes) |
| 48 | + for line in file: |
| 49 | + line_count += 1 |
| 50 | + word_count += len(line.split()) |
67 | 51 |
|
68 | | - if not count_lines and not count_words and not count_bytes: |
69 | | - total_output.append(total_lines) |
70 | | - total_output.append(total_words) |
71 | | - total_output.append(total_bytes) |
72 | | - |
73 | | - formatted_total = [] |
74 | | - |
75 | | - for number in total_output: |
76 | | - formatted_total.append(f"{number:3}") |
77 | | - print(" ".join(formatted_total), "total") |
| 52 | + byte_count = os.path.getsize(filename) |
| 53 | + |
| 54 | + total_lines += line_count |
| 55 | + total_words += word_count |
| 56 | + total_bytes += byte_count |
| 57 | + |
| 58 | + print( |
| 59 | + format_counts(line_count, word_count, byte_count), |
| 60 | + filename, |
| 61 | + ) |
| 62 | + |
| 63 | +if len(filenames) > 1: |
| 64 | + print( |
| 65 | + format_counts(total_lines, total_words, total_bytes), |
| 66 | + "total", |
| 67 | + ) |
0 commit comments