87470aamodule-04(ex{0..3}): fix bugs
4 files changed, +104, -83
@@ -26,8 +26,7 @@ def main() -> None:
2626 return
2727 finally:
2828 f.close()
29 -
30 - print(f"File '{filename}' closed.")
29+ print(f"File '{filename}' closed.")
3130
3231
3332 if __name__ == "__main__":
+40, -31
@@ -1,9 +1,45 @@
1 1 import sys
2 2
3 3
4+def transform(content: str) -> str:
5+ lines = content.splitlines()
6+ return "".join(line + "#\n" for line in lines)
7+
8+
9+def save(content: str) -> None:
10+ try:
11+ output_name = input("Enter new file name (or empty): ").strip()
12+ except (KeyboardInterrupt, EOFError):
13+ print("\nProgram interrupted by user.")
14+ return
15+
16+ if output_name == "":
17+ print("Not saving data.")
18+ return
19+
20+ print(f"Saving data to '{output_name}'")
21+ try:
22+ out = open(output_name, "w")
23+ except OSError as error:
24+ print(f"Error opening file '{output_name}': {error}")
25+ print("Data not saved.")
26+ return
27+
28+ try:
29+ out.write(content)
30+ except OSError as error:
31+ print(f"Error writing to file '{output_name}': {error}")
32+ print("Data not saved.")
33+ return
34+ finally:
35+ out.close()
36+
37+ print(f"Data saved in file '{output_name}'.")
38+
39+
440 def main() -> None:
541 if len(sys.argv) != 2:
6 - print("Usage: python3 ft_ancient_text.py <file>")
42+ print("Usage: python3 ft_archive_creation.py <file>")
743 return
844
945 filename = sys.argv[1]
@@ -26,40 +62,13 @@ def main() -> None:
2662 f.close()
2763 print(f"File '{filename}' closed.\n")
2864
29 - lines = content.splitlines()
30 - transformed = [line + "#" for line in lines]
31 - transformed_content = "\n".join(transformed)
32 -
65+ transformed = transform(content)
3366 print("Transform data:")
3467 print("---\n")
35 - print(transformed_content)
68+ print(transformed)
3669 print("\n---")
3770
38 - try:
39 - output_name = input("Enter new file name (or empty): ").strip()
40 - except (KeyboardInterrupt, EOFError):
41 - print("\nProgram interrupted by user.")
42 - return
43 -
44 - if output_name == "":
45 - print("Not saving data.")
46 - return
47 -
48 - print(f"Saving data to '{output_name}'")
49 - try:
50 - out = open(output_name, "w")
51 - except OSError as error:
52 - print(f"Error opening file '{output_name}': {error}")
53 - return
54 -
55 - try:
56 - out.write(transformed_content)
57 - except OSError as error:
58 - print(f"Error writing to file '{output_name}': {error}")
59 - finally:
60 - out.close()
61 -
62 - print(f"Data saved in file '{output_name}'.")
71+ save(transformed)
6372
6473
6574 if __name__ == "__main__":
@@ -2,10 +2,14 @@ import sys
2 2
3 3
4 4 def print_error(message: str) -> None:
5+ sys.stdout.flush()
5 6 sys.stderr.write(f"[STDERR] {message}\n")
7+ sys.stderr.flush()
6 8
7 9
8 -def get_input() -> str | None:
10+def read_line(prompt: str) -> str | None:
11+ sys.stdout.write(prompt)
12+ sys.stdout.flush()
913 try:
1014 line = sys.stdin.readline()
1115 except (KeyboardInterrupt, EOFError):
@@ -14,6 +18,39 @@ def get_input() -> str | None:
1418 return line.rstrip("\n")
1519
1620
21+def transform(content: str) -> str:
22+ lines = content.splitlines()
23+ return "".join(line + "#\n" for line in lines)
24+
25+
26+def save(content: str) -> None:
27+ output_name = read_line("Enter new file name (or empty): ")
28+ if output_name is None:
29+ return
30+ if output_name == "":
31+ print("Not saving data.")
32+ return
33+
34+ print(f"Saving data to '{output_name}'")
35+ try:
36+ out = open(output_name, "w")
37+ except OSError as error:
38+ print_error(f"Error opening file '{output_name}': {error}")
39+ print("Data not saved.")
40+ return
41+
42+ try:
43+ out.write(content)
44+ except OSError as error:
45+ print_error(f"Error writing to file '{output_name}': {error}")
46+ print("Data not saved.")
47+ return
48+ finally:
49+ out.close()
50+
51+ print(f"Data saved in file '{output_name}'.")
52+
53+
1754 def main() -> None:
1855 if len(sys.argv) != 2:
1956 print("Usage: python3 ft_ancient_text.py <file>")
@@ -39,42 +76,13 @@ def main() -> None:
3976 f.close()
4077 print(f"File '{filename}' closed.\n")
4178
42 - lines = content.splitlines()
43 - transformed = [line + "#" for line in lines]
44 - transformed_content = "\n".join(transformed)
45 -
79+ transformed = transform(content)
4680 print("Transform data:")
4781 print("---\n")
48 - print(transformed_content)
82+ print(transformed, end="")
4983 print("\n---")
5084
51 - print("Enter new file name(or empty): ", end="", flush=True)
52 - output_name = get_input()
53 -
54 - if output_name is None:
55 - return
56 - if output_name == "":
57 - print("Not saving data.")
58 - return
59 -
60 - print(f"Saving data to '{output_name}'")
61 - try:
62 - out = open(output_name, "w")
63 - except OSError as error:
64 - print_error(f"Error opening file '{output_name}': {error}")
65 - print("Data not saved.")
66 - return
67 -
68 - try:
69 - out.write(transformed_content)
70 - except OSError as error:
71 - print_error(f"Error writing to file '{output_name}': {error}")
72 - print("Data not saved.")
73 - return
74 - finally:
75 - out.close()
76 -
77 - print(f"Data saved in file '{output_name}'.")
85+ save(transformed)
7886
7987
8088 if __name__ == "__main__":
+22, -17
@@ -1,37 +1,42 @@
1 -def secure_archive(filename: str,
2 - mode: str = "read",
3 - content: str = ""
4 - ) -> tuple[bool, str]:
5 - try:
6 - if mode == "read":
1+def secure_archive(
2+ filename: str,
3+ mode: str = "read",
4+ content: str = ""
5+) -> tuple[bool, str]:
6+ if mode == "read":
7+ try:
7 8 with open(filename, "r") as f:
8 9 data = f.read()
910 return (True, data)
10 - elif mode == "write":
11+ except OSError as e:
12+ return (False, str(e))
13+ elif mode == "write":
14+ try:
1115 with open(filename, "w") as f:
1216 f.write(content)
1317 return (True, "Content successfully written to file")
14 - else:
15 - return (False, "Invalid mode. Use 'read' or 'write'")
16 - except Exception as error:
17 - return (False, str(error))
18+ except OSError as e:
19+ return (False, str(e))
20+ else:
21+ return (False, "Invalid mode. Use 'read' or 'write'")
1822
1923
2024 def main() -> None:
21 - print("=== Cyber Archibes Security ===\n")
25+ print("=== Cyber Archives Security ===\n")
2226
2327 print("Using 'secure_archive' to read from a nonexistent file:")
2428 print(secure_archive("/non/existing/file"))
2529
2630 print("\nUsing 'secure_archive' to read from an inaccessible file:")
27 - print(secure_archive("/etc/master.passwd"))
31+ print(secure_archive("/etc/shadow"))
2832
29 - contents = secure_archive("ancient_fragment.txt")
3033 print("\nUsing 'secure_archive' to read from a regular file:")
31 - print(contents)
34+ ok, data = secure_archive("ancient_fragment.txt")
35+ print((ok, data))
3236
33 - print("\nUsing 'secure_archive' to write previous content to a new file:")
34 - print(secure_archive("new_file.txt", "write", contents[1]))
37+ if ok:
38+ print("\nUsing 'secure_archive' to write previous content to a new file:")
39+ print(secure_archive("new_file.txt", "write", data))
3540
3641
3742 if __name__ == "__main__":