blob: 3395a38e508417c56b82dacc588922e246504945 (
plain)
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
|
#!/usr/bin/env python3
# Create a function secure_archive() that provides safe access to any file for
# reading or writing. It returns a tuple (True|False, str) that indicates
# whether the operation #succeeded (the boolean) and provides the associated
# content (either the file’s contents or an error message). The function takes
# the following parameters: a mandatory file name, an optional int or str
# (your choice) that indicates the action to perform (read or write), and
# another optional string that contains the content to write to the file.
# https://docs.python.org/3/library/functions.html#repr
def secure_archive(file: str, write=None, to_write=None) -> tuple[bool, str]:
try:
with open(file, "r") as f:
content = f.read()
if write is None:
return (True, content)
if write:
with open(file, "w") as f:
f.write(to_write)
return (True, to_write)
except FileNotFoundError as err:
content = f"{err}"
except PermissionError as err:
content = f"{err}"
except OSError as err:
content = f"{err}"
return (False, content)
def main() -> None:
to_write = "Content successfully write to file"
print("=== Cyber Archives Security ===")
print("Using 'secure archive' to read from a non-existent file:")
print(secure_archive("file_does_not_exist.txt"))
print()
print("Using 'secure archive' to read from accessible file:")
print(secure_archive("permission_issue.txt"))
print()
print("Using 'secure archive' to read a regular file:")
print(secure_archive("ancient_fragment.txt"))
print()
print("Using 'secure archive' to write content to file :")
# pass 1 to write
print(secure_archive("ancient_fragment.txt", 1, to_write))
if __name__ == "__main__":
main()
|