我用一个自己写的脚本通过ods文档从一个遗留产品上传数据。
当前实施:
import ezodf
from . import db
ezodf.config.set_table_expand_strategy('all')
current_spreadsheet = ezodf.opendoc(filename='./table1.ods')
current_table = current_spreadsheet.sheets[-1]
for row_num in range(current_table.nrows()):
db.session.add(
Model_1(
id=current_table['a%s' % row_num].value,
name=current_table['b%s' % row_num].value
)
)
db.session.commit()
由于表的数量非常可观并且它们具有不同的结构,所以我想像这样梳理代码:
with ezodf.opendoc(filename='./table1.ods') as spreadsheet:
with spreadsheet.sheets[-1] as table:
for row_num in range(table.nrows()):
db.session.add(
Model_1(
id=table['a%s' % row_num].value,
name=table['b%s' % row_num].value
)
)
但是当我运行第二个选项时,我得到以下信息:
File "uploader.py", line 36, in <module>
with ezodf.opendoc(filename='./table_1.ods') as spreadsheet:
AttributeError: __exit__
如何绕过/捕获此错误?
ezodf - 0.3.2
lxml - 3.7.2
python - 3.5
根据PEP-0343,构造
with ...需要一个实现方法的对象:__enter__()和__exit__():返回的对象没有实现
ezodf.opendoc(...)方法__exit__(),所以with ...不能使用。当然,您可以尝试通过从 classes 继承它来编写自己的类ezodf,但在我看来这有点过分了......这个对象甚至没有方法
.close(),所以如果你不改变文档,你可以只对不同的文档使用相同的变量。如果您更改,请不要忘记使用.save(...)或保存更改.saveas(...)您可以将文档处理安排为一项功能。
例子:
测试: