英文:
Why is dbf-table still open, if using "with tbl.open()"?
问题
我使用Ethan Furmans的dbf-python模块(版本0.99.3)。如果我使用这段代码:
import dbf
tbl = dbf.Table(os.path.join(db_pfad, tabelle + ".dbf"))
with tbl.open(mode=dbf.READ_ONLY) as tbl:
for rec in tbl:
...
一切都运行得很好。但是对于我对使用with
语句的理解,最后一行tbl.close()
应该是多余的。离开with
范围应该会关闭表格 - 不是吗?
无论如何:如果我省略了那行代码,表格就会保持打开状态!
这是dbf模块中的一个错误吗,还是我在python的with
语句方面理解有误?
英文:
I use Ethan Furmans dbf-python-module (v. 0.99.3). If I use this code:
import dbf
tbl = dbf.Table(os.path.join(db_pfad, tabelle + ".dbf"))
with tbl.open(mode=dbf.READ_ONLY) as tbl:
for rec in tbl:
...
tbl.close()
... everything is running fine.
But for my understanding of using with
-clause, the last line tbl.close()
should be redundant and superfluous. Leaving the range of with
should close the table - not?
Anyway: If I ommit that line, the table will be left open!
Is this a bug in dbf-module or something I didn't get right about with
-clause in python?
答案1
得分: 1
在进入with
块时,会检查表格是否已经打开,如果已打开,则在退出时保持打开状态 - 您可以使用.open()
调用手动打开它。
您想要做的是:
tbl = ...
with tbl:
# 做一些操作
这将以读/写模式打开表格,并在完成后关闭它。如果您需要以只读模式打开它,那么使用with
没有意义:
tbl = ...
tbl.open(dbf.READ_ONLY)
for rec in tbl:
# ...
table.close()
英文:
When the with
block is entered, the table is checked to see if it was already open, and if so leaves it open on exit -- and you are manually opening it with the .open()
call.
What you want to do is:
tbl = ...
with tbl:
# do stuff
That will open the table in read/write mode, and close it when done. If you need it to be opened read-only, then there's no point in using with
:
tbl = ...
tbl.open(dbf.READ_ONLY)
for rec in tbl:
...
table.close()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论