def save_list():
f = open('data.txt', 'w')
ii = 0
with itemMatrix[ii] as item:
f.write(item + '\n')
ii += 1这段代码一直给我错误:属性错误,在第5行输入( itemMatrixii作为item:)
为什么会发生这种事,我该怎么解决呢?如果需要更多的代码,请告诉我。
耽误您时间,实在对不起!
发布于 2019-11-06 15:10:10
def save_list():
with open('data.txt', 'w') as f:
for item in itemMatrix:
f.write(f"{item}\n")(使用F-字符串将元素格式化为换行符)。
发布于 2019-11-06 15:08:04
你可能想写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/
https://stackoverflow.com/questions/58732820
复制相似问题