Skip to content

Commit 3413558

Browse files
committed
wc command complete
1 parent bd591e3 commit 3413558

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

implement-shell-tools/wc/my_wc.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(
4+
prog="wc",
5+
description="Counts lines, words, and bytes in text files."
6+
)
7+
8+
parser.add_argument("-l", "--lines", action="store_true", help="Print the line counts")
9+
parser.add_argument("-w", "--words", action="store_true", help="Print the word counts")
10+
parser.add_argument("-c", "--bytes", action="store_true", help="Print the byte counts")
11+
parser.add_argument("paths", nargs="+", help="One or more files to process")
12+
13+
args = parser.parse_args()
14+
15+
if not (args.lines or args.words or args.bytes):
16+
args.lines = args.words = args.bytes = True
17+
18+
total_lines = total_words = total_bytes = 0
19+
20+
for path in args.paths:
21+
try:
22+
with open(path, "rb") as file:
23+
content = file.read()
24+
except Exception as e:
25+
print(f"wc: {path}: {e}")
26+
continue
27+
28+
lines = content.count(b'\n')
29+
words = len(content.decode('utf-8', errors='ignore').split())
30+
byte_count = len(content)
31+
32+
if args.lines:
33+
print(f"{lines:>8}", end=" ")
34+
if args.words:
35+
print(f"{words:>8}", end=" ")
36+
if args.bytes:
37+
print(f"{byte_count:>8}", end=" ")
38+
39+
print(f"{path}")
40+
41+
total_lines += lines
42+
total_words += words
43+
total_bytes += byte_count
44+
45+
if len(args.paths) > 1:
46+
if args.lines:
47+
print(f"{total_lines:>8}", end=" ")
48+
if args.words:
49+
print(f"{total_words:>8}", end=" ")
50+
if args.bytes:
51+
print(f"{total_bytes:>8}", end=" ")
52+
print("total")

0 commit comments

Comments
 (0)