|
11 | 11 |
|
12 | 12 | args = parser.parse_args() |
13 | 13 |
|
14 | | - |
15 | | -count_total_lines = 0 |
16 | | -count_total_words = 0 |
17 | | -count_total_bytes = 0 |
18 | | - |
19 | | -for file_path in args.path: |
20 | | - with open(file_path, "r") as file: |
21 | | - content = file.read() |
| 14 | +def calculate_counts(content): |
22 | 15 |
|
23 | 16 | count_lines = content.count("\n") |
24 | 17 | count_words = len(content.split()) |
25 | 18 | count_bytes = len(content.encode("utf-8")) |
| 19 | + |
| 20 | + return count_lines, count_words, count_bytes |
26 | 21 |
|
27 | | - count_total_lines += count_lines |
28 | | - count_total_words += count_words |
29 | | - count_total_bytes += count_bytes |
30 | | - |
| 22 | +def format_output(count_lines, count_words, count_bytes, file_path): |
31 | 23 | if not (args.l or args.w or args.c): |
32 | 24 | print(count_lines, count_words, count_bytes, file_path) |
33 | 25 | else: |
|
40 | 32 | line += f"{count_bytes} " |
41 | 33 | line += f"{file_path}" |
42 | 34 | print(line) |
| 35 | + |
| 36 | +count_total_lines = 0 |
| 37 | +count_total_words = 0 |
| 38 | +count_total_bytes = 0 |
| 39 | + |
| 40 | +for file_path in args.path: |
| 41 | + with open(file_path, "r") as file: |
| 42 | + content = file.read() |
| 43 | + |
| 44 | + count_lines, count_words, count_bytes = calculate_counts(content) |
| 45 | + |
| 46 | + count_total_lines += count_lines |
| 47 | + count_total_words += count_words |
| 48 | + count_total_bytes += count_bytes |
| 49 | + |
| 50 | + format_output(count_lines, count_words, count_bytes, file_path) |
| 51 | + |
43 | 52 | if len(args.path) > 1: |
44 | | - if not (args.l or args.w or args.c): |
45 | | - print(count_total_lines, count_total_words, count_total_bytes, " total") |
46 | | - else: |
47 | | - line = "" |
48 | | - if args.l: |
49 | | - line += f"{count_total_lines} " |
50 | | - if args.w: |
51 | | - line += f"{count_total_words} " |
52 | | - if args.c: |
53 | | - line += f"{count_total_bytes} " |
54 | | - line += " total" |
55 | | - print(line) |
| 53 | + format_output(count_total_lines, count_total_words, count_total_bytes, " total") |
0 commit comments