pythonfinally

finally: txt.close() SyntaxError in Python


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

Solution

  • Your try and except blocks exist only in your for loop and are executed for every iteration of the loop. Because of this, your finally block will not work as it has no try or except part. If you want to close the file after the loop, you can omit the finally block and just have txt.close() after the for loop:

    txt = open('temp5.txt','r')
    for i in range(5):
        try:
            10/i-50
            print(i)
        except:
            print('error:', i)
    txt.close()
    

    Additionally, you could also open the file using with to close it automatically:

    with open("temp5.txt") as txt:
        for i in range(5):
            try:
                10/i-50
                print(i)
            except:
                print('error:', i)