我有一个文件夹,其中有一堆dbf文件,我想要转换成csv。我尝试使用代码将扩展名从.dbf更改为.csv,当我使用Excel时这些文件打开得很好,但是当我在熊猫中打开它们时,它们看起来如下所示:
s\t�
0 NaN
1 1 176 1.58400000000e+005-3.385...
这不是我想要的,而且这些字符不会出现在真正的文件中。
如何正确读取dbf文件?
发布于 2015-09-24 23:42:39
从网上看,有几种选择:
用简化
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
发布于 2018-01-12 04:57:41
这是我多年来一直使用的解决方案。我有一个Python2.7的解决方案和一个Python3.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安装中获得dbfpy和dbfread。
发布于 2015-09-25 00:17:39
使用我的dbf库,您可以执行如下操作:
import sys
import dbf
for arg in sys.argv[1:]:
dbf.export(arg)
它将创建一个与每个dbf文件同名的.csv
文件。如果将该代码放入名为dbf2csv.py
的脚本中,则可以将其称为
python dbf2csv.py dbfname dbf2name dbf3name ...
https://stackoverflow.com/questions/32772447
复制相似问题