|
| 1 | +import argparse |
| 2 | +import os |
| 3 | + |
| 4 | +parser = argparse.ArgumentParser(description="wc command") |
| 5 | +parser.add_argument("file", help="File or directory to read") |
| 6 | +parser.add_argument("-l", dest="lines", action="store_true", help="count the number of lines") |
| 7 | +parser.add_argument("-w", dest="words", action="store_true", help="count the number of words") |
| 8 | +parser.add_argument("-c", dest="chars", action="store_true", help="count the number of characters") |
| 9 | +args = parser.parse_args() |
| 10 | + |
| 11 | +if os.path.isdir(args.file): |
| 12 | + files = os.listdir(args.file) |
| 13 | + for f in files: |
| 14 | + path = os.path.join(args.file, f) |
| 15 | + if os.path.isfile(path): |
| 16 | + with open(path, "r") as file_obj: |
| 17 | + text = file_obj.read() |
| 18 | + line_count = len(text.splitlines()) |
| 19 | + word_count = len(text.split()) |
| 20 | + char_count = len(text) |
| 21 | + |
| 22 | + if not (args.lines or args.words or args.chars): |
| 23 | + print(f"{line_count}\t{word_count}\t{char_count}\t{path}") |
| 24 | + continue |
| 25 | + output = [] |
| 26 | + if args.lines: |
| 27 | + output.append(str(line_count)) |
| 28 | + if args.words: |
| 29 | + output.append(str(word_count)) |
| 30 | + if args.chars: |
| 31 | + output.append(str(char_count)) |
| 32 | + output.append(path) |
| 33 | + print("\t".join(output)) |
| 34 | +else: |
| 35 | + |
| 36 | + with open(args.file, "r") as f: |
| 37 | + text = f.read() |
| 38 | + line_count = len(text.splitlines()) |
| 39 | + word_count = len(text.split()) |
| 40 | + char_count = len(text) |
| 41 | + if not (args.lines or args.words or args.chars): |
| 42 | + print(f"{line_count}\t{word_count}\t{char_count}\t{args.file}") |
| 43 | + else: |
| 44 | + output = [] |
| 45 | + if args.lines: |
| 46 | + output.append(str(line_count)) |
| 47 | + if args.words: |
| 48 | + output.append(str(word_count)) |
| 49 | + if args.chars: |
| 50 | + output.append(str(char_count)) |
| 51 | + output.append(args.file) |
| 52 | + print("\t".join(output)) |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
0 commit comments