Skip to content

Commit 3e13fb5

Browse files
committed
Complete cat.py
1 parent 4350f48 commit 3e13fb5

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import sys
2+
import argparse
3+
4+
parser = argparse.ArgumentParser(
5+
prog="cat",
6+
description="Reading the file and print the content",
7+
)
8+
9+
parser.add_argument("-n", help="Number all lines")
10+
parser.add_argument("-b", help="Number only lines with content")
11+
parser.add_argument("paths", nargs="+", help="The file path to process")
12+
13+
args = parser.parse_args()
14+
paths = args.paths
15+
16+
for path in paths:
17+
try:
18+
with open(path, "r") as f:
19+
content = f.read()
20+
lines = content.split("\n")
21+
lines.pop()
22+
23+
line_num = 1
24+
25+
for i in range(len(lines)):
26+
line = lines[i]
27+
if args.n:
28+
print(f"{line_num} {line}")
29+
line_num += 1
30+
31+
elif args.b:
32+
if line != "":
33+
print(f"{line_num} {line}")
34+
line_num += 1
35+
else:
36+
print(line)
37+
38+
except Exception as e:
39+
print(f"Error reading {path}: {e}")

0 commit comments

Comments
 (0)