-1

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
rawkiwi
  • 13
  • 1
  • 2
    the indentation of finally is wrong in the code snipped. It needs to be in the same column as try and except – Almos Jun 29 '22 at 09:41
  • Did you mean to use a context manager in the form: `with open('temp5.txt','r') as txt:` to automatically close the file? – quamrana Jun 29 '22 at 09:42
  • The indentation is flawed. Also, what were you hoping *10/i-50* would do (apart from raising a ZeroDivisionError exception)? – DarkKnight Jun 29 '22 at 09:50
  • 1
    The indentation you show implies the existence of a `for/finally` construct. This does not exist in python hence the syntax error. – quamrana Jun 29 '22 at 09:53

2 Answers2

3

Do you really need using open() and close()? I suggest you to use context managers, that will make your life easier:

with open("temp5.txt") as file:
    # Logic, exception handling, ...
blunova
  • 2,122
  • 3
  • 9
  • 21
2

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)
Raed Ali
  • 549
  • 1
  • 6
  • 22