如何在python中将dbf转换为csv?

2024-04-27 04:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹,里面有一堆dbf文件,我想转换成csv。我试过使用代码将扩展名从.dbf改为.csv,当我使用Excel时这些文件打开得很好,但是当我用panda打开它们时,它们看起来像这样:

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

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


Tags: 文件csv代码文件夹nan字符excelpanda
3条回答

编辑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/

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

geopandashttp://geopandas.org/

geopandashttps://gis.stackexchange.com/questions/129414/only-read-specific-attribute-columns-of-a-shapefile-with-geopandas-fionashp and dbf

从网上看,有几个选择:


使用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

使用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 ...

相关问题 更多 >