Skip to content

Commit 9bdb725

Browse files
committed
implement wc in oython with flags -wcl
1 parent 94e3a33 commit 9bdb725

2 files changed

Lines changed: 64 additions & 1 deletion

File tree

implement-shell-tools/ls/ls.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,4 @@
3131
print(f" ".join(entries))
3232

3333
except FileNotFoundError:
34-
print(f"ls: No such file or directory ")
34+
print(f"ls: {args.path}: No such file or directory.", file=sys.stderr)

implement-shell-tools/wc/wc.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import sys
5+
import os
6+
7+
parser = argparse.ArgumentParser(
8+
prog='wc',
9+
description='Displays number of words, lines, and bytes in a file'
10+
)
11+
12+
parser.add_argument('-l', '--lines', action='store_true', help='counts number of lines')
13+
parser.add_argument('-w', '--words', action='store_true', help='counts sequence of characters')
14+
parser.add_argument('-c', '--bytes', action='store_true', help='counts raw size of a file in bytes')
15+
parser.add_argument('files', nargs='+', help='Files to read')
16+
17+
args = parser.parse_args()
18+
19+
if not args.files:
20+
print(f"wc: missing file to read")
21+
sys.exit(1)
22+
23+
total_lines, total_words, total_bytes = 0, 0, 0
24+
25+
for file in args.files:
26+
try:
27+
with open(file, 'r') as f:
28+
content = f.read()
29+
30+
line_count = content.count('\n')
31+
word_count = len(content.split())
32+
byte_count = os.path.getsize(file)
33+
34+
total_lines += line_count
35+
total_words += word_count
36+
total_bytes += byte_count
37+
38+
show_all = not (args.lines or args.words or args.bytes)
39+
40+
output = ""
41+
if args.lines or show_all:
42+
output += f"{line_count:>7} "
43+
if args.words or show_all:
44+
output += f"{word_count:>7} "
45+
if args.bytes or show_all:
46+
output += f"{byte_count:>7} "
47+
48+
print(f"{output} {file}")
49+
50+
except FileNotFoundError:
51+
print(f"wc: {args.path}: No such file or directory.", file=sys.stderr)
52+
53+
54+
if len(args.files) > 1:
55+
total = ""
56+
if args.lines or show_all:
57+
total += f"{total_lines:>7} "
58+
if args.words or show_all:
59+
total += f"{total_words:>7} "
60+
if args.bytes or show_all:
61+
total += f"{total_bytes:>7} "
62+
63+
print(f"{total}total")

0 commit comments

Comments
 (0)