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}')