You want to ensure a file is always closed after reading, even if an error occurs. Which code correctly uses try-except-finally to do this?
Afile = open('data.txt')
try:
data = file.read()
except IOError:
print('Read error')
finally:
file.close()
Btry:
file = open('data.txt')
data = file.read()
except IOError:
print('Read error')
finally:
file.close()
Ctry:
file = open('data.txt')
data = file.read()
finally:
file.close()
except IOError:
print('Read error')
Dfile = open('data.txt')
try:
data = file.read()
finally:
file.close()
except IOError:
print('Read error')