Python: UnboundLocalError: local variable 'open' referenced before assignment

def read_lines():
    readFileName = "readfile.txt"
    f = open(readFileName, 'r+')
    contents = f.read()
        ... # and so on 

read_lines()

When I run this, I get an error message:

f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
+3
source share
1 answer

This means that further in your function you create a variable with the name open:

open = ...

Rename it so that it does not interfere with the built-in function.

+13
source

All Articles