AttributeError:即使发送了电子邮件,

系统教程 行业动态 更新时间:2024-06-14 17:02:18
AttributeError:即使发送了电子邮件,__ exit__也会出错(AttributeError: __exit__ error even though email is sent)

我试图只在excel文件非空时发送电子邮件(数据超出标题),否则不做任何事情。 这可能是我忽略的一些愚蠢的东西,但下面的查询引发了一个AttributeError: __exit__错误。 我认为with声明应该已经考虑到了这一点( f.close() )。

你介意检查什么是错的吗? 谢谢! 请注意,无论错误如何,实际上都会发送电子邮件,但是不会打印else语句中的消息。

with xlrd.open_workbook('name.xlsx').sheet_by_index(0) as f: if len(f.readlines()) > 1: insert script to send email # If excel is not empty, send output via Email else: print('No new data') # dont send email

I am trying to only send the email when excel file is non empty (there is data beyond the header), and do nothing otherwise. This is probably something stupid I am overlooking, but the query below is throwing an AttributeError: __exit__ error. I thought the with statement should have taken care of that (f.close()).

Would you mind checking what's wrong please? Thank you! Please note that regardless of the error, the email is actually sent, but the message in the else statement is not printed.

with xlrd.open_workbook('name.xlsx').sheet_by_index(0) as f: if len(f.readlines()) > 1: insert script to send email # If excel is not empty, send output via Email else: print('No new data') # dont send email

最满意答案

在这种情况下, f是表格,而不是工作簿。 另外,如果你想close被调用,你将不得不将它包装在contextlib.closing() ; 只与上下文管理器with工作。

你可以尝试类似的东西:

import contextlib with contextlib.closing(xlrd.open_workbook('name.xlsx')) as workbook: f = workbook.sheet_by_index(0) if f.nrows > 0: pass # has rows else: pass # has no rows

但我很确定workbook不保留任何资源。 我认为他们甚至没有close方法。

f in this case is the sheet, not the workbook. Also, if you want close to be called you would have to wrap it in contextlib.closing(); with only works with context managers.

You could try something like:

import contextlib with contextlib.closing(xlrd.open_workbook('name.xlsx')) as workbook: f = workbook.sheet_by_index(0) if f.nrows > 0: pass # has rows else: pass # has no rows

But I'm pretty sure workbooks don't maintain any resources. I don't think they even have a close method.

更多推荐

本文发布于:2023-04-21 18:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/fd1957247729d0a2fda05250d20af1c3.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:送了   电子邮件   AttributeError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!