-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.py
More file actions
36 lines (29 loc) · 982 Bytes
/
cat.py
File metadata and controls
36 lines (29 loc) · 982 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import argparse
parser = argparse.ArgumentParser(
prog="cat",
description="read, display, and concatenate text files.",
)
parser.add_argument("-n", action="store_true", help="Number all output lines.")
parser.add_argument("-b", action="store_true", help="Number non-blank output lines.")
parser.add_argument("paths",nargs="+", help="The file to search")
args = parser.parse_args()
for path in args.paths:
try:
with open(path, mode='r', encoding='utf-8') as f:
lines = f.readlines()
except Exception as err:
print(f"Error reading file '{path}': {err}")
continue
line_num = 1
for line in lines:
if args.b:
if line.strip() != "":
print(f"{line_num:5} {line}", end="")
line_num += 1
else:
print()
elif args.n:
print(f"{line_num:5} {line}", end="")
line_num += 1
else:
print(line, end="")