How to use try, except, finally with file to close a file if error occur in Python

1 Answer

0 votes
try:
    f = open("d:\\file.txt")
    f.write("Python Programming")
except:
    print("Error writing to file")
finally:
    f.close()
    print("file closed")

'''
run:
 
Error writing to file
file closed

'''

 



answered Nov 25, 2018 by avibootz

Related questions

2 answers 286 views
1 answer 168 views
168 views asked Sep 11, 2018 by avibootz
1 answer 164 views
164 views asked Jul 11, 2022 by avibootz
1 answer 224 views
224 views asked Jun 4, 2021 by avibootz
1 answer 219 views
219 views asked Nov 23, 2020 by avibootz
...