在python中将dbf转换为csv的方法?

Ste*_*ter 2 python csv dbf pandas

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

                                                s\t?
0                                                NaN
1            1       176 1.58400000000e+005-3.385...
Run Code Online (Sandbox Code Playgroud)

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

小智 5

这是我多年来一直使用的解决方案。我有一个适用于 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
Run Code Online (Sandbox Code Playgroud)

蟒蛇 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
Run Code Online (Sandbox Code Playgroud)

您可以从 pip install 获取 dbfpy 和 dbfread。