【发布时间】:2019-12-30 21:14:35
【问题描述】:
我开始学习一些 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
我的理解是 inFile 变量只会在块内存在/有效。但是block之后的inFile.close()调用不会导致程序崩溃或者抛出异常吗?
类似地,wlist 是在块内声明的,但我在方法结束时返回 wlist 没有问题。
谁能帮助解释为什么它会这样工作?也许我对 with blocks 的理解是不正确的。
【问题讨论】:
-
见 stackoverflow.com/questions/45100271/…
with不创建范围 -
重复调用
.close(),请参阅here。with语句仅指定应对语句中的对象(如文件对象)执行清理。
标签: python python-3.x with-statement