python:UnboundLocalError:赋值前引用的局部变量'open'

时间:2022-01-05 03:50:43
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

1 个解决方案

#1


13  

This means that further down in your function you create a variable called open:

这意味着在函数中进一步向下创建一个名为open的变量:

open = ...

Rename it so that it doesn't * with the built-in function.

重命名它,使其不与内置函数冲突。

#1


13  

This means that further down in your function you create a variable called open:

这意味着在函数中进一步向下创建一个名为open的变量:

open = ...

Rename it so that it doesn't * with the built-in function.

重命名它,使其不与内置函数冲突。