Skip to main content
 首页 » 编程设计

python之使用 python 验证一个 shapefile 是一个 shapefile (fiona, ogr)

2025年05月04日7powertoolsteam

在 fiona 1.5.0 上(我很困惑为什么各种文件(例如 .dbf 和 .gdb)不打印我的“不是 Shapefile!”(这是我想要的文件不是 . shp) 退出前警告。

import fiona 
import sys 
 
   def process_file(self, in_file, repair_file): 
        with fiona.open(in_file, 'r', encoding='utf-8') as input: 
            # check that the file type is a shapefile 
            if input.driver == 'ESRI Shapefile': 
                print "in_file is a Shapefile!" 
            else: 
                print "NOT a Shapefile!" 
                exit() 
            with fiona.open(repair_file, 'r') as repair: 
                # check that the file type is a shapefile 
                if repair.driver == 'ESRI Shapefile': 
                    print "Verified that repair_file is a Shapefile!" 
                else: 
                    print "NOT a Shapefile!" 
                    exit() 

对于 gdb 我得到一个错误,fiona 不支持驱动程序(因为 ogr 确实让我感到惊讶)- 并且没有打印语句:

>> fiona.errors.DriverError: unsupported driver: u'OpenFileGDB' 

对于 .dbf,我实际上得到了这个:

>> Verified that in_file is a Shapefile! 
>> Verified that repair_file is a Shapefile! 

请您参考如下方法:

有了 OGR,ESRI Shapefile驱动程序读取 DBF 文件。要检查数据源是否只有属性而没有几何(即只有 DBF 文件),请检查元数据中的几何类型以查看它是否为 'None'。

import fiona 
with fiona.open(file_name) as ds: 
    geom_type = ds.meta['schema']['geometry'] 
    print('geometry type: ' + geom_type) 
    if geom_type == 'None': 
        print('no geometry column, so probably just a DBF file') 

此外,最近向 fiona 添加了对 OpenFileGDB 的只读支持。更新您的包,看看它是否有效。