diff options
Diffstat (limited to 'py04/ex3')
| -rwxr-xr-x | py04/ex3/ft_vault_security.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/py04/ex3/ft_vault_security.py b/py04/ex3/ft_vault_security.py new file mode 100755 index 0000000..3395a38 --- /dev/null +++ b/py04/ex3/ft_vault_security.py @@ -0,0 +1,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() |
