|
| 1 | +import argparse |
| 2 | +import glob |
| 3 | +import os |
| 4 | + |
| 5 | +def count_file(file_path, count_lines=False, count_words=False, count_bytes=False): |
| 6 | + lines = words = bytes_count = 0 |
| 7 | + with open(file_path, "r", encoding="utf-8", errors="ignore") as f: |
| 8 | + for line in f: |
| 9 | + lines += 1 |
| 10 | + words += len(line.split()) |
| 11 | + bytes_count = os.path.getsize(file_path) |
| 12 | + |
| 13 | + if not (count_lines or count_words or count_bytes): |
| 14 | + return lines, words, bytes_count |
| 15 | + |
| 16 | + return ( |
| 17 | + lines if count_lines else None, |
| 18 | + words if count_words else None, |
| 19 | + bytes_count if count_bytes else None |
| 20 | + ) |
| 21 | + |
| 22 | +def main(): |
| 23 | + parser = argparse.ArgumentParser(description="count lines, words, and bytes like the wc command") |
| 24 | + parser.add_argument("-l", action="store_true", help="Count lines") |
| 25 | + parser.add_argument("-w", action="store_true", help="Count words") |
| 26 | + parser.add_argument("-c", action="store_true", help="Count bytes") |
| 27 | + parser.add_argument("path", nargs="+", help="Files to count") |
| 28 | + |
| 29 | + args = parser.parse_args() |
| 30 | + |
| 31 | + total_lines = total_words = total_bytes = 0 |
| 32 | + file_list = [] |
| 33 | + for pattern in args.path: |
| 34 | + file_list.extend(glob.glob(pattern)) |
| 35 | + |
| 36 | + for file_path in file_list: |
| 37 | + counts = count_file(file_path, args.l, args.w, args.c) |
| 38 | + |
| 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) |
| 57 | + |
| 58 | + 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") |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + main() |
0 commit comments