【问题标题】:Way to convert dbf to csv in python?在python中将dbf转换为csv的方法?
【发布时间】:2015-09-24 23:18:45
【问题描述】:

我有一个文件夹,里面有一堆我想转换为 csv 的 dbf 文件。我尝试使用代码将扩展名从 .dbf 更改为 .csv,当我使用 Excel 时,这些文件可以正常打开,但是当我在 pandas 中打开它们时,它们看起来像这样:

                                                s\t�
0                                                NaN
1            1       176 1.58400000000e+005-3.385...

这不是我想要的,而且这些字符不会出现在真实文件中。
如何正确读取 dbf 文件?

【问题讨论】:

    标签: python csv pandas dbf


    【解决方案1】:

    这是我多年来一直使用的解决方案。我有一个适用于 Python 2.7 的解决方案和一个适用于 Python 3.5(可能也是 3.6)的解决方案。

    Python 2.7:

    import csv
    from dbfpy import dbf
    
    def dbf_to_csv(out_table):#Input a dbf, output a csv
        csv_fn = out_table[:-4]+ ".csv" #Set the table as .csv format
        with open(csv_fn,'wb') as csvfile: #Create a csv file and write contents from dbf
            in_db = dbf.Dbf(out_table)
            out_csv = csv.writer(csvfile)
            names = []
            for field in in_db.header.fields: #Write headers
                names.append(field.name)
            out_csv.writerow(names)
            for rec in in_db: #Write records
                out_csv.writerow(rec.fieldData)
            in_db.close()
        return csv_fn
    

    Python 3.5:

    import csv
    from dbfread import DBF
    
    def dbf_to_csv(dbf_table_pth):#Input a dbf, output a csv, same name, same path, except extension
        csv_fn = dbf_table_pth[:-4]+ ".csv" #Set the csv file name
        table = DBF(dbf_table_pth)# table variable is a DBF object
        with open(csv_fn, 'w', newline = '') as f:# create a csv file, fill it with dbf content
            writer = csv.writer(f)
            writer.writerow(table.field_names)# write the column name
            for record in table:# write the rows
                writer.writerow(list(record.values()))
        return csv_fn# return the csv name
    

    您可以通过 pip install 获取 dbfpy 和 dbfread。

    【讨论】:

      【解决方案2】:

      使用my dbf library,您可以执行以下操作:

      import sys
      import dbf
      for arg in sys.argv[1:]:
          dbf.export(arg)
      

      这将创建一个与每个 dbf 文件同名的 .csv 文件。如果您将该代码放入名为dbf2csv.py 的脚本中,则可以将其称为

      python dbf2csv.py dbfname dbf2name dbf3name ...
      

      【讨论】:

      • Ethan,您的图书馆有任何文档吗?
      • @N4v:不是真的。不过,Stackoverflow 上有很多整洁的东西。
      【解决方案3】:

      上网看看,有几个选择:


      simpledbf:

      dbf = Dbf5('fake_file_name.dbf')
      df = dbf.to_dataframe()
      

      从要点调整:

      import pysal as ps
      
      def dbf2DF(dbfile, upper=True):
          "Read dbf file and return pandas DataFrame"
          with ps.open(dbfile) as db:  # I suspect just using open will work too
              df = pd.DataFrame({col: db.by_col(col) for col in db.header})
              if upper == True: 
                 df.columns = map(str.upper, db.header) 
              return df
      

      【讨论】:

      • 我从仅有几行的脚本中调用了您的函数 dbf2DF。调用open导致如下错误:AttributeError: exit
      • 奇怪。 with 块需要__exit__,也许出于某种原因他们不赞成这样做?试试 db = ps.open(dbfile) 和 dedent。
      • 确实,没有“with”关键字,代码可以正常工作。谢谢!
      【解决方案4】:

      编辑#2:

      可以使用dbfread(只需使用pip install dbfread 安装)逐行读取dbf 文件,无需转换为csv:

      >>> from dbfread import DBF
      >>> for row in DBF('southamerica_adm0.dbf'):
      ...     print row
      ... 
      OrderedDict([(u'COUNTRY', u'ARGENTINA')])
      OrderedDict([(u'COUNTRY', u'BOLIVIA')])
      OrderedDict([(u'COUNTRY', u'BRASIL')])
      OrderedDict([(u'COUNTRY', u'CHILE')])
      OrderedDict([(u'COUNTRY', u'COLOMBIA')])
      OrderedDict([(u'COUNTRY', u'ECUADOR')])
      OrderedDict([(u'COUNTRY', u'GUYANA')])
      OrderedDict([(u'COUNTRY', u'GUYANE')])
      OrderedDict([(u'COUNTRY', u'PARAGUAY')])
      OrderedDict([(u'COUNTRY', u'PERU')])
      OrderedDict([(u'COUNTRY', u'SURINAME')])
      OrderedDict([(u'COUNTRY', u'U.K.')])
      OrderedDict([(u'COUNTRY', u'URUGUAY')])
      OrderedDict([(u'COUNTRY', u'VENEZUELA')])
      

      我更新的参考资料:

      项目官方网站:http://pandas.pydata.org

      官方文档:http://pandas-docs.github.io/pandas-docs-travis/

      dbfread:https://pypi.python.org/pypi/dbfread/2.0.6

      geopandas:http://geopandas.org/

      shp and dbfgeopandas: https://gis.stackexchange.com/questions/129414/only-read-specific-attribute-columns-of-a-shapefile-with-geopandas-fiona

      【讨论】:

      • 是的,我在“文档”一词下添加了文档链接,现在我已经明确报告了。
      • 请注意,这实际上不是 pandas 的官方文档站点,我认为 PANDA 完全是另外一回事(但我不清楚是什么)
      • 我现在注意到我的解决方案不是最优的。最好dbfread
      猜你喜欢
      • 2011-04-23
      • 2013-08-28
      • 2020-03-31
      • 2020-03-07
      • 2011-05-25
      • 2012-12-06
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多