-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
85 lines (70 loc) · 2.45 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import argparse
import sys
from file_processing import (
file_exists,
get_byte_count,
get_character_count,
get_line_count,
get_word_count,
process_file,
)
def print_message(filename: str, results: dict) -> None:
print_order = ["lines", "words", "bytes", "characters"]
message = []
for key_to_search in print_order:
result = results.get(key_to_search, False)
if result:
message.append(str(result))
if filename:
message.append(filename)
message_to_print: str = "\t".join(message)
print(message_to_print)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog="ccwc",
description="Finds the number of bytes, words, characters, and multibyte characters in a text file",
)
parser.add_argument(
"-c", "--byte", help="count the number of bytes", action="store_true"
)
parser.add_argument(
"-l", "--line", help="count the number of lines", action="store_true"
)
parser.add_argument(
"-w", "--word", help="count the number of words", action="store_true"
)
parser.add_argument(
"-m", "--char", help="count the number of characters", action="store_true"
)
parser.add_argument("filename", nargs="?", help="the filename to be checked")
args = parser.parse_args()
if args.filename and not file_exists(args.filename):
raise argparse.ArgumentTypeError(f"The file {args.filename} does not exist.")
if args.filename:
try:
with open(args.filename, "rb") as f:
fileAsBytes = f.read()
except PermissionError:
print(f"Incorrect permissions for {args.filename}")
sys.exit(1)
except OSError:
print(f"Could not open {args.filename}")
sys.exit(1)
else:
fileAsBytes = sys.stdin.buffer.read()
funcs_to_run = []
if not any([args.byte, args.line, args.word, args.char]):
funcs_to_run.append(get_line_count)
funcs_to_run.append(get_word_count)
funcs_to_run.append(get_byte_count)
else:
if args.byte:
funcs_to_run.append(get_byte_count)
if args.line:
funcs_to_run.append(get_line_count)
if args.word:
funcs_to_run.append(get_word_count)
if args.char:
funcs_to_run.append(get_character_count)
results = process_file(fileAsBytes, funcs_to_run)
print_message(args.filename, results)