How to Convert a DBF to a CSV in Python?

Background

πŸ’‘ A dBase database file (DBF) is a database file format with the .dbf file extension used by various applications and database systems.

πŸ’‘ A comma-separated values (CSV) file is a text file that uses a comma to separate fields of a data record (=line).

Problem Formulation

Given a .dbf file my_db.dbf. How to convert it to a CSV file my_db.csv?

Method 1: dbfread Module

To convert a DBF file to a CSV file in Python, use the dbfread module, create a DBF() object, and iterate over all dbf records using this object. You can then easily write one row/record at a time by using the csv.writer() functionality.

You may need to install the following two libraries using pip:

  • pip install dbfpy
  • pip install dbfread

Here’s how you can check if those libraries are already installed in your environment.

As soon as you’re sure the libraries are installed, run the following code to convert your DBF file to a CSV in Python:

import csv
from dbfread import DBF


def dbf_to_csv(path):
    '''Converting the .dbf at the specified path and
       returns the name of the .csv file after conversion.

       The .csv file has same path and naming scheme. Examples:
       (1) my_file.dbf --> my_file.csv
       (2) /path/to/file/my_file.dbf --> /path/to/file/my_file.csv
    '''

    # Set the name of the CSV file
    csv_path = path[:-4] + ".csv"

    # Create a DBF object, i.e., load the .dbf file into the code 
    dbf = DBF(path)

    # Create a CSV file and fill it with dbf data
    with open(csv_path, 'w', newline = '') as f:

        # Create the CSV writer
        writer = csv.writer(f)

        # Write the CSV column names
        writer.writerow(dbf.field_names)

        # Write the CSV rows
        for record in dbf:
            writer.writerow(list(record.values()))

    return csv_path

dbf_to_csv('my_file.dbf')

I modified and cleaned up the code from here.

Method 2: dbf Module

To convert one or multiple .dbf files to CSV files, install the dbf module and run dbf.export(path) or dbf.export(path_1, path_2, ...) in your Python shell.

Make sure to install the dbf module using the following command in your command line or shell:

pip install dbf

After installation, run the following code in your Python script to convert a DBF to a CSV file in Python:

import dbf
dbf.export('my_file.dbf')

You can export multiple files by passing multiple string path arguments in the dbf.export() function.

Like so:

import dbf
dbf.export('my_file_1.dbf', 'my_file_2.dbf', 'my_file_3.dbf')

Related: Python’s dbf library


Programmer Humor

❓ Question: Why do programmers always mix up Halloween and Christmas?
❗ Answer: Because Oct 31 equals Dec 25.

(If you didn’t get this, read our articles on the oct() and int() Python built-in functions!)