我有一个包含一堆 dbf 文件的文件夹,我想将其转换为 csv。我曾尝试使用代码将扩展名从 .dbf 更改为 .csv,当我使用 Excel 时这些文件可以正常打开,但是当我在 pandas 中打开它们时它们看起来像这样:
s\t�
0 NaN
1 1 176 1.58400000000e+005-3.385...
这不是我想要的,那些字符不会出现在真实文件中。
如何正确读入dbf文件?
最佳答案
这是我多年来一直使用的解决方案。我有一个适用于 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 安装中获取 dbfpy 和 dbfread。
关于python - 在 python 中将 dbf 转换为 csv 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772447/