Skip to content

Commit d193496

Browse files
Boshra MahmoudiBoshra Mahmoudi
authored andcommitted
implement wc with python
1 parent 60d49b2 commit d193496

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

  • implement-shell-tools/wc

‎implement-shell-tools/wc/wc.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import argparse
2+
3+
4+
parser = argparse.ArgumentParser()
5+
6+
parser.add_argument("-l", action="store_true")
7+
parser.add_argument("-w", action="store_true")
8+
parser.add_argument("-c", action="store_true")
9+
parser.add_argument("files", nargs="+")
10+
11+
args = parser.parse_args()
12+
13+
14+
def add_count(output, value):
15+
output.append(str(value))
16+
17+
18+
total_lines = 0
19+
total_words = 0
20+
total_bytes = 0
21+
22+
for filename in args.files:
23+
24+
with open(filename, "rb") as file:
25+
content = file.read()
26+
27+
lines = content.count(b"\n")
28+
words = len(content.split())
29+
bytes_count = len(content)
30+
31+
total_lines += lines
32+
total_words += words
33+
total_bytes += bytes_count
34+
35+
if not args.l and not args.w and not args.c:
36+
print(f"{lines:8} {words:8} {bytes_count:8} {filename}")
37+
38+
else:
39+
output = []
40+
41+
if args.l:
42+
add_count(output, lines)
43+
44+
if args.w:
45+
add_count(output, words)
46+
47+
if args.c:
48+
add_count(output, bytes_count)
49+
50+
print(f"{' '.join(output):>8} {filename}")
51+

0 commit comments

Comments
 (0)