Skip to content

Commit ff86f10

Browse files
added python code for the wc exercise
1 parent 1900a28 commit ff86f10

File tree

1 file changed

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

1 file changed

+37
-0
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import argparse
2+
3+
def wc(path, count_lines, count_words, count_bytes):
4+
try:
5+
with open(path, 'r') as f:
6+
content = f.read()
7+
lines = content.splitlines()
8+
words = content.split()
9+
bytes_ = len(content.encode('utf-8'))
10+
11+
parts = []
12+
if count_lines: parts.append(str(len(lines)))
13+
if count_words: parts.append(str(len(words)))
14+
if count_bytes: parts.append(str(bytes_))
15+
16+
if not parts:
17+
parts = [str(len(lines)), str(len(words)), str(bytes_)]
18+
print(' '.join(parts), path)
19+
20+
except FileNotFoundError:
21+
print(f"wc: {path}: No such file or directory")
22+
except IsADirectoryError:
23+
print(f"wc: {path}: Is a directory")
24+
25+
def main():
26+
parser = argparse.ArgumentParser()
27+
parser.add_argument('-l', action='store_true', help='Count lines')
28+
parser.add_argument('-w', action='store_true', help='Count words')
29+
parser.add_argument('-c', action='store_true', help='Count bytes')
30+
parser.add_argument('paths', nargs='+', help='Files to count')
31+
args = parser.parse_args()
32+
33+
for path in args.paths:
34+
wc(path, args.l, args.w, args.c)
35+
36+
if __name__ == "__main__":
37+
main()

0 commit comments

Comments
 (0)