python: UnboundLocalError: local variable 'open' referenced before assignment
Question:
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:
f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
Answers:
This means that further down in your function you create a variable called open
:
open = ...
Rename it so that it doesn’t clash with the built-in function.
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:
f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
This means that further down in your function you create a variable called open
:
open = ...
Rename it so that it doesn’t clash with the built-in function.