【发布时间】:2020-08-12 14:17:04
【问题描述】:
在下面的代码中,有没有办法在with-block 之外访问变量utterances_dict?下面的代码显然会返回错误:ValueError: I/O operation on closed file.
from csv import DictReader
utterances_dict = {}
utterance_file = 'toy_utterances.csv'
with open(utterance_file, 'r') as utt_f:
utterances_dict = DictReader(utt_f)
for line in utterances_dict:
print(line)
【问题讨论】:
-
为什么要在外面使用?只需将您的 for 循环放入 with 结构中即可?
-
我知道在这种情况下该怎么做。但实际的方案更加多元化
-
这不行吗?:定义一个函数,在该函数中使用 with 然后返回你想要的,使用返回的数据
-
@Ruli - 这可行;我会玩弄那个。谢谢。
标签: python with-statement