I can not use finally:txt.close() to close a txt file. Please help me out. Thank you!
txt = open('temp5.txt','r')
for i in range(5):
try:
10/i-50
print(i)
except:
print('error:', i)
finally:
txt.close()
Error:
File "C:\Users\91985\AppData\Local\Temp/ipykernel_12240/2698394632.py", line 9
finally:
^
SyntaxError: invalid syntax
I was confused because this part was good without error:
txt = open('temp5.txt','r')
for i in range(5):
try:
10/i-50
print(i)
except:
print('error:', i)
Output:
error: 0
1
2
3
4
Your
tryandexceptblocks exist only in yourfor loopand are executed for every iteration of the loop. Because of this, yourfinallyblock will not work as it has notryorexceptpart. If you want to close the file after the loop, you can omit thefinallyblock and just havetxt.close()after the for loop:Additionally, you could also open the file using
withto close it automatically: