Skip to content

Commit 56fa8c1

Browse files
committed
main simplified using the read_files method: by separating logic and tigher exception handling
1 parent 68a9ce0 commit 56fa8c1

File tree

1 file changed

+19
-38
lines changed
  • implement-shell-tools/cat

1 file changed

+19
-38
lines changed

implement-shell-tools/cat/cat.py

Lines changed: 19 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import argparse
22
import sys
33

4+
45
def read_files(paths):
56
lines = []
67
for path in paths:
@@ -11,61 +12,41 @@ def read_files(paths):
1112
print(f"Error reading {path}: {e}", file=sys.stderr)
1213
sys.exit(1)
1314
return lines
14-
15+
16+
1517
def main():
1618
parser = argparse.ArgumentParser(
1719
prog="display-content-of-a-file",
18-
description="cat is used to display the content of a file or print the content of a file."
20+
description="cat is used to display the content of a file or print the content of a file.",
1921
)
20-
parser.add_argument('-n', action='store_true', help='number output lines')
21-
parser.add_argument('-b', action='store_true', help='number non-empty output lines')
22-
parser.add_argument('paths', nargs='+', help="The file path(s) to process")
22+
23+
parser.add_argument("-n", action="store_true", help="number output lines")
24+
parser.add_argument("-b", action="store_true", help="number non-empty output lines")
25+
parser.add_argument("paths", nargs="+", help="The file path(s) to process")
2326

2427
options = parser.parse_args()
2528

26-
combined_data = ""
27-
for path in options.paths:
28-
try:
29-
with open(path, 'r', encoding='utf-8') as f:
30-
combined_data += f.read() + "\n"
31-
except Exception as e:
32-
print(f"Error reading {path}: {e}", file=sys.stderr)
33-
sys.exit(1)
29+
lines = read_files(options.paths)
3430

35-
# If user used -b
3631
if options.b:
3732
line_num = 1
38-
numbered_lines = []
39-
for line in combined_data.split('\n'):
40-
if line.strip() == '':
41-
numbered_lines.append(line) # Keep empty lines unnumbered
42-
else:
43-
numbered_lines.append(f"{line_num:6} {line}")
33+
for line in lines:
34+
if line.strip():
35+
print(f"{line_num:6} {line}")
4436
line_num += 1
45-
sys.stdout.write('\n'.join(numbered_lines) + '\n')
37+
else:
38+
print(line)
4639

47-
# If user used -n
4840
elif options.n:
49-
numbered_lines = [
50-
f"{i+1:6} {line}"
51-
for i, line in enumerate(combined_data.split('\n'))
52-
]
53-
sys.stdout.write('\n'.join(numbered_lines) + '\n')
41+
for i, line in enumerate(lines, start=1):
42+
print(f"{i:6} {line}")
5443

55-
# If user didn't use -n or -b
5644
else:
57-
sys.stdout.write(combined_data)
45+
for line in lines:
46+
print(line)
47+
5848

5949
if __name__ == "__main__":
6050
main()
6151

62-
63-
64-
65-
66-
67-
68-
69-
70-
7152
#python3 cat.py -b sample-files/*

0 commit comments

Comments
 (0)