From 5d84a1ff65dfb5b1dabf65ff5d3b2800c5490f37 Mon Sep 17 00:00:00 2001 From: Seaswimmer Date: Wed, 5 Jun 2024 23:55:53 -0400 Subject: [PATCH] add files --- .gitignore | 3 ++- files/__init__.py | 0 files/main.py | 10 ++++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 files/__init__.py create mode 100644 files/main.py diff --git a/.gitignore b/.gitignore index ed8ebf5..49cd206 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -__pycache__ \ No newline at end of file +__pycache__ +files/test.txt diff --git a/files/__init__.py b/files/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/files/main.py b/files/main.py new file mode 100644 index 0000000..4b2758e --- /dev/null +++ b/files/main.py @@ -0,0 +1,10 @@ +if __name__ == '__main__': # prevent this code from running whenever this file is imported in another file as a module + file_path = "test.txt" # we will be opening this file + try: # catch any exceptions that are thrown in the following block + with open(file_path, 'w') as f: # open the file (this is a context manager, so it automatically handles closing the file descriptor once we're done with it) + f.write('Hello, World!\n') # write to the file + except Exception as e: # if an exception is raised, catch it and process it + if isinstance(e, PermissionError): # if the exception being caught is a PermissionsError, execute the following code + print(f'Cannot write to file {file_path}, permission denied') + else: # if not, execute the following code + print(f'Cannot write to file {file_path}\n{e}')