|
| 1 | +import argparse |
| 2 | +# ------------------------------------------- |
| 3 | +# Set up the argument parser |
| 4 | +# ------------------------------------------- |
| 5 | + |
| 6 | +parser = argparse.ArgumentParser( |
| 7 | + prog ="display-file-content", |
| 8 | + description = "Implement cat command with -n and -b flag support", |
| 9 | + ) |
| 10 | + |
| 11 | +parser.add_argument("-n", "--number-all-lines", |
| 12 | + action="store_true", |
| 13 | + help="Number every line in the file" |
| 14 | + ) |
| 15 | + |
| 16 | +parser.add_argument("-b", "--number-non-empty-lines", |
| 17 | + action="store_true", |
| 18 | + help="Number non empty lines in the file" |
| 19 | + ) |
| 20 | + |
| 21 | +parser.add_argument("paths", nargs="+", help="File paths to process") |
| 22 | + |
| 23 | +args = parser.parse_args() |
| 24 | + |
| 25 | +# ------------------------------------------- |
| 26 | +# Implement functionality |
| 27 | +# ------------------------------------------- |
| 28 | + |
| 29 | +line_number = 1 |
| 30 | + |
| 31 | +for filepath in args.paths: |
| 32 | + with open(filepath, "r", encoding="utf-8") as f: |
| 33 | + content = f.read() |
| 34 | + |
| 35 | + lines = content.split("\n") |
| 36 | + |
| 37 | + for line in lines: |
| 38 | + if args.number_all_lines: |
| 39 | + print(f"{line_number} {line}") |
| 40 | + line_number += 1 |
| 41 | + |
| 42 | + elif args.number_non_empty_lines: |
| 43 | + if line.strip() == "": |
| 44 | + print(line) |
| 45 | + else: |
| 46 | + print(f"{line_number} {line}") |
| 47 | + line_number +=1 |
| 48 | + |
| 49 | + else: |
| 50 | + print(line) |
0 commit comments