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
Asked By: RRR

||

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.

Answered By: NPE
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.