我试图只在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 emailI 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 rowsBut I'm pretty sure workbooks don't maintain any resources. I don't think they even have a close method.
更多推荐
发布评论