Skip to content

Commit 17b2b5b

Browse files
committed
basic (wc)
1 parent e8ac9af commit 17b2b5b

File tree

1 file changed

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

1 file changed

+25
-0
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import argparse
2+
3+
def count_file(filename):
4+
try:
5+
with open(filename, "r", encoding="utf-8") as f:
6+
content = f.read()
7+
lines = content.count("\n")
8+
words = len(content.split())
9+
bytes_ = len(content.encode("utf-8"))
10+
return lines, words, bytes_
11+
except FileNotFoundError:
12+
print(f"wc: {filename}: No such file or directory")
13+
return 0, 0, 0
14+
15+
def main():
16+
parser = argparse.ArgumentParser(description="Python version of wc")
17+
parser.add_argument("files", nargs="+", help="Files to count")
18+
args = parser.parse_args()
19+
20+
for filename in args.files:
21+
lines, words, bytes_ = count_file(filename)
22+
print(f"{lines:7} {words:7} {bytes_:7} {filename}")
23+
24+
if __name__ == "__main__":
25+
main()

0 commit comments

Comments
 (0)