-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcat.py
More file actions
48 lines (43 loc) · 1.62 KB
/
cat.py
File metadata and controls
48 lines (43 loc) · 1.62 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
import argparse
import glob
def main():
parser = argparse.ArgumentParser(description="cat with -n and -b options")
parser.add_argument("-n", action="store_true", help="Number all output lines")
parser.add_argument("-b", action="store_true", help="Number non-blank lines (overrides -n)")
parser.add_argument("files", nargs="+", help="Files to read (supports *.txt)")
args = parser.parse_args()
# -b overrides -n
number_all = args.n
number_nonblank = args.b
if number_all and number_nonblank:
number_all = False
# Expand wildcard patterns (e.g. *.txt)
file_list = []
for pattern in args.files:
matched_files = glob.glob(pattern)
if matched_files:
file_list.extend(matched_files)
else:
file_list.append(pattern)
# Print contents of each file
line_number = 1
for filename in file_list:
try:
with open(filename, "r") as f:
for line in f:
text = line.rstrip("\n")
if number_nonblank:
if text.strip(): # only number non-blank lines
print(f"{line_number:6}\t{text}")
line_number += 1
else:
print()
elif number_all:
print(f"{line_number:6}\t{text}")
line_number += 1
else:
print(text)
except FileNotFoundError:
print(f"cat: {filename}: No such file or directory")
if __name__ == "__main__":
main()