11 lines
862 B
Python
11 lines
862 B
Python
|
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}')
|