为什么我会收到矩阵的属性错误 __enter__?

Why am I getting an attribute error __enter__ for a matrix?

def save_list():  
  f = open('data.txt', 'w')

  ii = 0

  with itemMatrix[ii] as item:

    f.write(item + '\n')

    ii += 1

这段代码一直给我错误: 属性错误 enter on line 5, (with itemMatrix[ii] as item:)

为什么会这样,我该如何解决?如果需要更多代码,请告诉我。

感谢您的宝贵时间!

你可能想写 for item in itemMatrix[ii]:

with 语句使用上下文管理协议。 它大致翻译成这个。

with obj as instance:
  body(instance)

# is syntactical suger for
instance = obj.__enter__()
try:
    body(instance)
except BaseException as e:
    obj.__exit__(type(e), e, stacktrace)
else:
    obj.__exit__(None, None, None)

如果您想使用 with 语句,那么 itemMatrix[ii] 应该有一个 enter 方法和一个 exit 方法。见 https://www.python.org/dev/peps/pep-0343/

def save_list():
    with open('data.txt', 'w') as f:
        for item in itemMatrix:
            f.write(f"{item}\n")

(使用 f-strings 将元素与换行符一起格式化。)