|
1 | 1 | import os |
| 2 | +import sys |
2 | 3 | import argparse |
3 | 4 |
|
4 | 5 | def ls(path, one_column, show_hidden): |
5 | 6 | """List files in a directory, optionally in one column or including hidden files.""" |
6 | 7 | try: |
| 8 | + if os.path.isfile(path): |
| 9 | + print(os.path.basename(path)) |
| 10 | + return |
| 11 | + |
7 | 12 | files = os.listdir(path) |
8 | | - if not show_hidden: |
| 13 | + |
| 14 | + if show_hidden: |
| 15 | + files = ['.', '..'] + files |
| 16 | + else: |
9 | 17 | files = [f for f in files if not f.startswith('.')] |
| 18 | + |
10 | 19 | files.sort() |
11 | | - |
| 20 | + |
12 | 21 | if one_column: |
13 | 22 | print(*files, sep='\n') |
14 | 23 | else: |
15 | 24 | print(*files) |
| 25 | + |
16 | 26 | except FileNotFoundError: |
17 | | - print(f"ls: cannot access '{path}': No such file or directory") |
| 27 | + print( |
| 28 | + f"ls: cannot access '{path}': No such file or directory", |
| 29 | + file=sys.stderr |
| 30 | + ) |
18 | 31 | except NotADirectoryError: |
19 | | - print(f"ls: cannot access '{path}': Not a directory") |
| 32 | + print( |
| 33 | + f"ls: cannot access '{path}': Not a directory", |
| 34 | + file=sys.stderr |
| 35 | + ) |
20 | 36 |
|
21 | 37 | def main(): |
22 | 38 | parser = argparse.ArgumentParser() |
23 | 39 | parser.add_argument('-1', dest='one_column', action='store_true', help='list one file per line') |
24 | 40 | parser.add_argument('-a', action='store_true', help='show hidden files') |
25 | 41 | parser.add_argument('path', nargs='?', default='.', help='directory to list') |
26 | 42 | args = parser.parse_args() |
27 | | - |
| 43 | + |
28 | 44 | ls(args.path, args.one_column, args.a) |
29 | 45 |
|
30 | 46 | if __name__ == "__main__": |
|
0 commit comments