python - 使用 Python "with"语句进行 ogr.open(file)

标签 python file geospatial ogr

是否可以使用Python "with"使用 ogr.open(file) 函数的语句?

例如,我想做这样的事情:

with ogr.open(file) as ds:

目前,我只能执行以下操作:

try:
    ds = ogr.open(file)
    ...

except:
    del ds

最佳答案

根据文档,您似乎无法将 与 ogr.Open(file) 一起使用 ...

with 语句中使用的 Python 对象需要具有方法 __enter____exit__ 来设置和删除所使用的上下文在 with block 内。 Here's an explanation .

根据Documentation for OGR Open ,这些 __enter____exit__ 方法不是为 Open 返回的 DataSource 对象定义的,因此您无法使用 ogr.Open 的结果 作为 with 语句的主语。

所以看来您必须使用 try/ except 组合(尽管 try/finally 组合可能会更好)。

关于python - 使用 Python "with"语句进行 ogr.open(file),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37981614/

相关文章:

google-maps - 如何找到多段线的重叠以便在谷歌地图上绘制阴影的公共(public)线段

python - 无法在python的绘图表面图中更改轴标题

python - 如何计算 MATLAB 中不包括周末的时间戳之间的营业时间?

python - 我需要更改当前数据框的格式。我应该怎么做?

c - 从 .map 文件获取数据

flutter - 如何从目录导入所有 Dart 文件?

Python - 分类的最低方差的箱大小

file - 如何导入java.nio.file包

sql - 在 JOIN 之后添加简单的 AND 会降低性能

mongodb - 将 $near 与 $maxDistance 和 $and 一起使用可以充当 MongoDB 中的过滤器吗?