Python 访问块内部声明的变量,而块外部声明的变量-为什么它可以工作?

Python 访问块内部声明的变量,而块外部声明的变量-为什么它可以工作?,python,python-3.x,with-statement,Python,Python 3.x,With Statement,我开始学习一些Python并了解with块 以下是我的代码: def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...")

我开始学习一些Python并了解with块

以下是我的代码:

def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.

Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
with open(WORDLIST_FILENAME, 'r') as inFile:
    line = inFile.readline()
    wlist = line.split()
    print("  ", len(wlist), "words loaded.")
print(wlist[0])
inFile.close()
return wlist
我的理解是infle变量只在块内存在/有效。但是块之后的infle.close()调用不会使程序崩溃或引发异常吗

类似地,wlist在块内声明,但我对在方法末尾返回wlist没有问题


有人能解释为什么它是这样工作的吗?也许我对with块的理解是不正确的。

您可以读取with块中的变量,因为with语句没有向您的程序添加任何作用域,它只是一条语句,用于在调用with块中引用的对象时使代码更干净

这:

输出与以下内容相同:

file = open('file.txt', 'r') 
f = file.read()
file.close()

print(f)

因此,主要区别在于使代码更干净

请参见
with
不会创建作用域重复调用
.close()
,请参见。
with
语句仅指定应该对语句中的对象(如文件对象)执行清理。
file = open('file.txt', 'r') 
f = file.read()
file.close()

print(f)