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

标签 python csv pandas dbf

我有一个包含一堆 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/

相关文章:

python - 在 Python/Pandas 中创建带有元数据头的 csv 文件,后跟时间序列

python - 在 Pandas 数据框中查找列和索引

python - Python标准库中的类JavaScript对象?

python - 在 Python 中按键对字典列表进行排序

R,截取一个csv文件以从链接下载

python - pandas 用左引号和右引号解析 csv

mysql - 将具有不同日期格式的 CSV 导入 MySQL

python - 使用 Python (Selenium) 选择提交按钮

python - 在 Windows 上启动时运行 Python 程序

python - 如何让我的 python 程序运行得更快?