为什么在使用 “with tbl.open()” 后,dbf 表仍然处于打开状态?

huangapple go评论65阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2023年2月6日 05:31:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定