如何在with语句中使as套件中的VAR成为绑定到with作用域的非全局变量?在下面的示例中,在with语句之后也在with外部将f变量赋值
with open("some_text.txt") as f:
pass
print(f.closed)
print(f)这将返回:
>>> True
<_io.TextIOWrapper name='some_text.txt' mode='r' encoding='UTF-8'>即使我在函数中使用with,as变量仍然是绑定的:
def longerThan10Chars(*files):
for my_file in files:
with open(my_file) as f:
for line in f:
if len(line) >= 10:
print(line)
print(f.closed)在这里,f.closed仍然打印True。
发布于 2016-09-23 03:22:01
Python作用域边界是函数,没有别的。没有将with块设置为作用域的选项;如果必须将其设置为单独的作用域,则将其放入函数中;as目标只是另一个本地对象,不会存在于该新函数之外。
或者,只需显式删除该名称,即可使该名称在with语句后消失:
with open("some_text.txt") as f:
pass
del f发布于 2016-09-23 03:23:04
要删除f的绑定,请执行以下操作:
del locals()['f']您必须手动执行此操作。with...as块不能为您做到这一点。
https://stackoverflow.com/questions/39647214
复制相似问题