The short version
To convert a DBF to CSV in Python, read it with dbfread and write it with the standard csv module: about ten lines, shown below. pandas has no DBF reader of its own, so pandas users go through dbfread too. Four things decide whether the CSV is right: deleted rows (dbfread skips them silently), the code page (old files are not UTF-8, and some declare nothing), memo fields (their text lives in a separate .dbt or .fpt file), and the CSV's own encoding (Excel wants a BOM). Without Python, the free DBF to CSV converter on this site does it in the browser and reports the code page and missing memo files.
The test files
If you only need to look inside the file, How to Open a DBF File on Windows 11 and Mac covers that, and DBF to Excel Without Losing Dates or Leading Zeros is the one for spreadsheets. This guide is about CSV.
I used our converter's DBF test fixtures plus a few built with the same byte-level builder:
| File | What is in it |
|---|---|
orders.dbf |
Declares cp1252. Three records, one of them marked deleted. A character ORDER_NO with leading zeros, accented names, a date column with one empty date, a TOTAL of type N with 2 decimals. |
notes.dbf + notes.dbt |
A memo column whose text is in the .dbt, one note containing a comma and a line break. |
memo_orphan.dbf |
A memo column and no .dbt next to it. |
russian.dbf |
Russian text, declares cp866. |
nocp.dbf |
The same bytes as russian.dbf with the code page byte set to 00, so it declares nothing. |
Versions: Python 3.12.8, dbfread 2.0.7, pandas 2.2.0, on a Mac.
Convert DBF to CSV in Python with dbfread
dbfread installs with pip install dbfread per its install page. Its export page shows the pattern: the standard library csv module, a header row from the field names, then one row per record. Here it is with the two arguments the docs' example leaves out:
import csv
from dbfread import DBF
table = DBF("orders.dbf")
print(table.dbversion, table.encoding, "header says", table.header.numrecords, "records")
print("records:", len(table.records), "deleted:", len(table.deleted))
with open("orders.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(table.field_names)
for record in table:
writer.writerow(record.values())
FoxBASE+/Dbase III plus, no memory cp1252 header says 3 records
records: 2 deleted: 1
ORDER_NO,CUSTOMER,ORDERED,TOTAL
000101,Café Rouge,1998-03-17,1234.5
000103,Müller GmbH,,0.1
newline="" is what the csv module docs ask for: without it, newlines inside quoted fields are not handled correctly and on Windows an extra \r gets added. encoding="utf-8" matters because, per the open() docs, Python before 3.15 uses the locale's encoding when you give none; 3.15 makes UTF-8 the default.
Look at what came out. ORDER_NO kept its zeros, because a C field is a string in dbfread. The date is ISO 1998-03-17, because the field types table maps D to datetime.date and the csv module writes non-strings with str(). The empty date became an empty field: dbfread returned None, and the csv docs say None is written as the empty string. The total lost its trailing zero: 1234.50 became 1234.5, because dbfread returns N fields as int or float. Same value, but the declared scale is gone.
And the file has three records in its header but two rows in the CSV.
Where did the deleted rows go?
A DBF never removes a row when the application deletes it. Microsoft's table file structure page for Visual FoxPro says each record begins with a delete flag byte: a space means live, an asterisk means deleted. The row is still in the file, bytes and all.
Iterating a DBF object gives only the live records. The deleted ones are still reachable: the dbfread introduction says "Deleted records are available in deleted". There is no ignore_deleted switch in dbfread; I checked the signature of DBF() in 2.0.7 and the DBF objects reference, and neither has one. You choose by which attribute you iterate. To keep everything and say which is which:
with open("orders_all.csv", "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(table.field_names + ["DELETED"])
for r in table.records:
w.writerow(list(r.values()) + [0])
for r in table.deleted:
w.writerow(list(r.values()) + [1])
ORDER_NO,CUSTOMER,ORDERED,TOTAL,DELETED
000101,Café Rouge,1998-03-17,1234.5,0
000103,Müller GmbH,,0.1,0
000102,Cancelled Ltd,1998-03-18,99.0,1
The deleted rows come after the live ones, so the original order is gone. Whether deleted rows belong in the export is a business question, not a technical one; ask before you drop them.
The code page
Text in old DBF files is single-byte text in a DOS or Windows code page. dbfread reads the code page byte from the header and decodes with it, and per the DBF objects reference "If this fails it falls back on ASCII". The fallback is where scripts break:
>>> DBF("russian.dbf").encoding
'cp866'
>>> [r["NAME"] for r in DBF("russian.dbf")]
['Привет', 'Мир']
>>> t = DBF("nocp.dbf"); t.encoding
'ascii'
>>> list(t)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 0: ordinal not in range(128)
>>> [r["NAME"] for r in DBF("nocp.dbf", encoding="cp866")]
['Привет', 'Мир']
Same bytes, and the only difference is the byte at offset 29. If you know where the file came from, pass encoding= yourself: cp866 is Russian DOS and cp1252 Western European Windows in Python's standard encodings table. Avoid char_decode_errors="replace" as a fix: it silences the error by writing replacement characters into your CSV. Garbled Text in Old DBF Files: Code Pages Explained goes further into picking the right one.
Memo fields
With notes.dbt sitting next to notes.dbf, dbfread found it on its own (table.memofilename printed notes.dbt) and the memo text came through. The csv module quoted the note with a comma and kept the line break inside the quotes, which is correct CSV and is why newline="" matters:
ID,NOTES
1,"First call, wants invoices re-sent."
2,"Line one
Line two, with a comma"
Without the .dbt, dbfread raises MissingMemoFile. ignore_missing_memofile=True lets the rest of the table through and, per the DBF objects reference, returns every memo as None, which becomes an empty field. Nothing in the CSV tells you the notes were lost, so go and find the companion file. FoxPro Memo Fields (.FPT): Getting the Text Out has more on those files.
DBF to CSV with pandas
pandas cannot read a DBF by itself. The pandas IO reference lists readers for CSV, Excel, Parquet, SAS, Stata, SPSS and others, and none for dBase; hasattr(pandas, "read_dbf") printed False on 2.2.0. The route is the one on dbfread's export page, DataFrame(iter(table)):
import pandas as pd
from dbfread import DBF
df = pd.DataFrame(iter(DBF("orders.dbf")))
print(df.dtypes.to_dict())
df.to_csv("orders_pd.csv", index=False)
{'ORDER_NO': dtype('O'), 'CUSTOMER': dtype('O'), 'ORDERED': dtype('O'), 'TOTAL': dtype('float64')}
b'ORDER_NO,CUSTOMER,ORDERED,TOTAL\n000101,Caf\xc3\xa9 Rouge,1998-03-17,1234.5\n000103,M\xc3\xbcller GmbH,,0.1\n'
Same values as the csv module, with the same deleted row missing, since pandas got the same iterator. Two differences show in the raw bytes. Lines end in \n here where the csv module wrote \r\n: to_csv defaults lineterminator to os.linesep, while the csv module's default is \r\n. And TOTAL is a float column for the whole frame. Use pandas when you want to clean or filter first; for a straight conversion it adds nothing.
DBF to CSV on Linux or Mac from the command line
DuckDB is the command-line tool I reach for with CSV and Parquet, so I tried it first. It does not read DBF. With the DuckDB 1.3.1 CLI:
$ duckdb -c "SELECT * FROM 'orders.dbf';"
Binder Error: No extension found that is capable of reading the file "orders.dbf"
$ duckdb -c "INSTALL dbf FROM community;"
HTTP Error: Failed to download extension "dbf" at URL "http://community-extensions.duckdb.org/v1.3.1/osx_arm64/dbf.duckdb_extension.gz" (HTTP 404)
The Python package, duckdb 1.5.5, gave the same Binder Error and the same 404 for its version. in2csv, ogr2ogr and LibreOffice were not installed on this machine, so I am not covering them. What does work anywhere Python and dbfread are installed is a one-liner that writes to standard output:
$ python -c 'import csv,sys; from dbfread import DBF; t=DBF(sys.argv[1]); w=csv.writer(sys.stdout); w.writerow(t.field_names); w.writerows(r.values() for r in t)' orders.dbf > orders.csv
$ cat orders.csv
ORDER_NO,CUSTOMER,ORDERED,TOTAL
000101,Café Rouge,1998-03-17,1234.5
000103,Müller GmbH,,0.1
On my Mac the bytes came out as UTF-8 (Café is 43 61 66 c3 a9). Add encoding="cp866" (or whatever the file needs) to DBF() for files that declare nothing.
Batch convert a folder of DBF files to CSV
A folder from an old system rarely holds one table. This script converts each one, keeps going when one fails, and prints what happened per file:
import csv
import sys
from pathlib import Path
from dbfread import DBF
src, dst = Path(sys.argv[1]), Path(sys.argv[2])
dst.mkdir(exist_ok=True)
for path in sorted(src.glob("*.[dD][bB][fF]")):
try:
table = DBF(path, ignore_missing_memofile=True)
out = dst / (path.stem + ".csv")
with open(out, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(table.field_names)
n = 0
for record in table:
writer.writerow(record.values())
n += 1
print(f"{path.name}: {n} rows, {len(table.deleted)} deleted skipped, {table.encoding}")
except Exception as exc:
print(f"{path.name}: FAILED {type(exc).__name__}: {exc}")
$ python batch.py in out
hostile.dbf: 2 rows, 0 deleted skipped, ascii
memo_orphan.dbf: 2 rows, 0 deleted skipped, cp1252
nocp.dbf: FAILED UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 0: ordinal not in range(128)
notes.dbf: 2 rows, 0 deleted skipped, cp1252
orders.dbf: 2 rows, 1 deleted skipped, cp1252
russian.dbf: 2 rows, 0 deleted skipped, cp866
western.dbf: 2 rows, 0 deleted skipped, cp1252
The glob catches both .dbf and .DBF. In the log, ascii means the file declared no code page; hostile.dbf got away with it because its text is plain digits, and nocp.dbf did not. And the failed file still left a nocp.csv behind with only the header in it, because the CSV was opened before the first record was decoded. Delete it, or write to a temporary name and rename on success. ignore_missing_memofile=True keeps the batch moving, so memo_orphan.csv has empty notes.
Which encoding should the CSV be?
UTF-8, and with a BOM if people will double-click it in Excel. Microsoft's page on opening CSV UTF-8 files correctly in Excel says a UTF-8 CSV opens normally "if it was saved with BOM (Byte Order Mark)", and otherwise points you at Data, Get Data, From Text/CSV. In Python that is encoding="utf-8-sig", which per the codecs docs writes 0xef 0xbb 0xbf first:
$ xxd orders_all.csv | head -1
00000000: efbb bf4f 5244 4552 5f4e 4f2c 4355 5354 ...ORDER_NO,CUST
The same docs say that in UTF-8 "the use of the BOM is discouraged". A reader that does not expect it keeps the three bytes as part of the first column name; Python's own csv module does, unless you open the file as utf-8-sig:
>>> next(csv.reader(open("orders_all.csv", encoding="utf-8")))
['\ufeffORDER_NO', 'CUSTOMER', 'ORDERED', 'TOTAL', 'DELETED']
>>> next(csv.reader(open("orders_all.csv", encoding="utf-8-sig")))
['ORDER_NO', 'CUSTOMER', 'ORDERED', 'TOTAL', 'DELETED']
So: BOM for a person with Excel, none for a database load. Writing the CSV in the DBF's old code page only hands the problem to the next person.
DBF to CSV without Python
The DBF to CSV converter on this site takes the .dbf, or a zip of the .dbf with its .dbt or .fpt, and returns a CSV. I ran the converter's own reader and writer from the repo on the same files:
from app.converter.router import READERS, WRITERS
data = READERS["dbf"](src / f"{name}.dbf")
files = WRITERS["csv"](data, out)
== orders
DBF_ENCODING_DECLARED: The file declares code page cp1252; text was decoded with it.
column ORDER_NO TEXT 6 None
column CUSTOMER TEXT 20 None
column ORDERED DATE None None
column TOTAL DECIMAL 10 2
orders.csv no BOM
ORDER_NO,CUSTOMER,ORDERED,TOTAL
000101,Café Rouge,1998-03-17,1234.50
000103,Müller GmbH,,0.10
...
== memo_orphan
DBF_MEMO_FILE_MISSING: Memo columns (NOTES) store their text in a separate .dbt or .fpt file, which was not uploaded alongside the .dbf. Those columns will be empty. Upload both files together in a ZIP to include them.
...
== nocp
DBF_ENCODING_GUESSED: The file declares no code page - normal for dBase III and Clipper files. cp866 looked the most plausible. If accented or Cyrillic text came out wrong, re-run with an explicit encoding.
nocp.csv no BOM
ID,NAME
1,Привет
2,Мир
Differences from the dbfread script: N fields with decimals are read as exact decimals, so 1234.50 keeps its scale. A file with no code page gets a guess, tried across several DOS and Windows code pages, and a warning that says it was a guess, where dbfread fails. A missing memo file is named in a warning instead of passing silently. The memo text from notes.dbt came through the same, line break and all.
Two things it does the same as the script, and you should know them. It skips deleted rows, with no warning: orders.csv has two rows and nothing says a third existed. And its CSV is UTF-8 without a BOM, which suits a database load; for Excel, open it through Data, From Text/CSV, or convert to .xlsx instead.
What each route did with the same files
| dbfread + csv | pandas | Our converter | |
|---|---|---|---|
| Deleted row | skipped, in table.deleted |
skipped | skipped, no warning |
| Declared code page | used | used | used, reported |
| No code page, non-ASCII text | UnicodeDecodeError |
same | guessed, warned |
| Date | 1998-03-17 |
1998-03-17 |
1998-03-17 |
| Empty date | empty field | empty field | empty field |
| N with 2 decimals | 1234.5 |
1234.5 |
1234.50 |
| Missing memo file | error, or empty with ignore_missing_memofile |
same | empty, warned |
| CSV encoding | what you pass to open() |
utf-8 default |
UTF-8, no BOM |
| Line endings | \r\n |
os.linesep |
\r\n |
Sources
- Table File Structure, Microsoft Learn, Visual FoxPro
- Opening CSV UTF-8 files correctly in Excel, Microsoft Support
- dbfread: Installing, Introduction, DBF Objects, Field Types, Exporting data
- csv: CSV File Reading and Writing and open(), Python docs
- codecs: standard encodings and utf-8-sig, Python docs
- pandas Input/output reference and DataFrame.to_csv