Skip to content

Commit ad8aad7

Browse files
committed
implement wc
1 parent 2e46884 commit ad8aad7

File tree

1 file changed

+59
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+59
-0
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import argparse
2+
import os
3+
4+
parser = argparse.ArgumentParser(
5+
prog="wc",
6+
description="Display numbers of line, words, and bytes in each file"
7+
)
8+
9+
parser.add_argument("-l", action="store_true", help="Number of lines")
10+
parser.add_argument("-w", action="store_true" ,help="Number of words")
11+
parser.add_argument("-c", action="store_true" ,help="Number of bytes")
12+
parser.add_argument("paths", nargs="+", help="The file to search")
13+
14+
args = parser.parse_args()
15+
16+
totalLines = 0
17+
totalWords = 0
18+
totalBytes = 0
19+
20+
lines = args.l
21+
words = args.w
22+
bytes = args.c
23+
24+
for path in args.paths:
25+
try:
26+
with open(path, "r") as f:
27+
content = f.read()
28+
29+
except Exception as err:
30+
print(f"Error reading file '{path}': {err}")
31+
continue
32+
33+
lineCount = len(content.split("/n"))
34+
wordCount = len(content.split())
35+
byteCount = os.path.getsize(path)
36+
37+
totalLines += lineCount
38+
totalWords += wordCount
39+
totalBytes += byteCount
40+
41+
if lines:
42+
print(f"\t{lineCount} {path}")
43+
lineCount += 1
44+
elif words:
45+
print(f"\t{wordCount} {path}")
46+
elif bytes:
47+
print(f"\t{byteCount} {path}")
48+
else:
49+
print(f"\t{lineCount} \t{wordCount} \t{byteCount} {path}")
50+
51+
if len(args.paths) > 1:
52+
if lines:
53+
print(f"{totalLines} total")
54+
elif words:
55+
print(f"{totalWords} total")
56+
elif bytes:
57+
print(f"{totalBytes} total")
58+
else:
59+
print(f"\t{totalLines} \t{totalWords} \t{totalBytes} total")

0 commit comments

Comments
 (0)