|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
| 7 | + |
| 8 | +# Set up the argument parser |
| 9 | +def parse_args(): |
| 10 | + parser = argparse.ArgumentParser( |
| 11 | + prog="list_files_in_directory", |
| 12 | + description="Implement ls commands to list files in directory" |
| 13 | + ) |
| 14 | + |
| 15 | + parser.add_argument( |
| 16 | + "-1","--file-per-line", |
| 17 | + action="store_true", |
| 18 | + dest="file_per_line", |
| 19 | + help="list files one per line" |
| 20 | + ) |
| 21 | + |
| 22 | + parser.add_argument( |
| 23 | + "-a", |
| 24 | + "--files-and-hidden-ones", |
| 25 | + action="store_true", |
| 26 | + dest="files_and_hidden_ones", |
| 27 | + help="list all files including hidden ones", |
| 28 | + ) |
| 29 | + |
| 30 | + parser.add_argument( |
| 31 | + "paths", |
| 32 | + nargs="*", |
| 33 | + help="directories to list" |
| 34 | + ) |
| 35 | + |
| 36 | + return parser.parse_args() |
| 37 | + |
| 38 | +# if no paths, default to current directory |
| 39 | +def get_paths(args): |
| 40 | + if len(args.paths) == 0: |
| 41 | + return ["."] |
| 42 | + return args.paths |
| 43 | + |
| 44 | +# list a single directory |
| 45 | +def list_directory(directory_path, show_hidden, file_per_line): |
| 46 | + try: |
| 47 | + entries = os.listdir(directory_path) |
| 48 | + except OSError as err: |
| 49 | + print(f"ls: cannot access '{directory_path}': {err}", file=sys.stderr) |
| 50 | + return |
| 51 | + |
| 52 | + if not show_hidden: |
| 53 | + entries = [name for name in entries if not name.startswith(".")] |
| 54 | + |
| 55 | + if file_per_line: |
| 56 | + for name in entries: |
| 57 | + print(name) |
| 58 | + else: |
| 59 | + print(" ".join(entries)) |
| 60 | + |
| 61 | +def main(): |
| 62 | + args = parse_args() |
| 63 | + paths = get_paths(args) |
| 64 | + |
| 65 | + for directory_path in paths: |
| 66 | + list_directory( |
| 67 | + directory_path=directory_path, |
| 68 | + show_hidden=args.files_and_hidden_ones, |
| 69 | + file_per_line=args.file_per_line, |
| 70 | + ) |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments