Reputation: 25
I am learning about exceptions in python and I am having trouble with some code. the following code is:
try:
txt = open("C:\\Users\\Draco\\OneDrive\\Documents\\textfile.txt","r")
try:
txt.write("This is a test. Normal service will shortly resume!")
finally:
print("Content written to file successfully. Have a nice day.")
txt.close()
except IOError:
print("Error: unable to write the file. Check permissions")
Now when I execute the code I get the following to two lines: Content written to file successfully. Have a nice day. Error: unable to write the file. Check permissions
The issues I am having is that because the error, in this case being the "r" which should be "w" I should only get the message Error: unable to write the file. Check permissions. But I am getting both error and the success messages and I am unsure why
Upvotes: 0
Views: 37
Reputation: 2012
I'll break it down one by one for you.
Try block opened
try:
File opened with read privileges.
txt = open("C:\\Users\\Draco\\OneDrive\\Documents\\textfile.txt","r")
Try block opened, exception occurred when you wrote since you wrote to a readonly file object.
try:
txt.write("This is a test. Normal service will shortly resume!")
Since you have an inner try block, the nested finally is the first block executed.
finally:
Printing success even though the file write failed.
print("Content written to file successfully. Have a nice day.")
Closing the file, works fine
txt.close()
Exception handler, now the exception is handled.
except IOError:
print("Error: unable to write the file. Check permissions")
Upvotes: 1
Reputation: 164613
finally
always executes:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
The process you are seeing:
txt = open(loc, 'r')
because at the stage it is not
writing any data.txt.write
it errors and moves to finally
,
for the reason given above.IOError
, you will also see the message
defined in your except
clause.Upvotes: 0