Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert .csv file into .dbf using Python?

How can I convert a .csv file into .dbf file using a python script? I found this piece of code online but I'm not certain how reliable it is. Are there any modules out there that have this functionality?

like image 416
djq Avatar asked Dec 14 '10 15:12

djq


2 Answers

Using the dbf package you can get a basic csv file with code similar to this:

import dbf
some_table = dbf.from_csv(csvfile='/path/to/file.csv', to_disk=True)

This will create table with the same name and either Character or Memo fields and field names of f0, f1, f2, etc.

For a different filename use the filenameparameter, and if you know your field names you can also use the field_names parameter.

some_table = dbf.from_csv(csvfile='data.csv', filename='mytable',
        field_names='name age birth'.split())

Rather basic documentation is available here.

Disclosure: I am the author of this package.

like image 94
Ethan Furman Avatar answered Oct 24 '22 12:10

Ethan Furman


You won't find anything on the net that reads a CSV file and writes a DBF file such that you can just invoke it and supply 2 file-paths. For each DBF field you need to specify the type, size, and (if relevant) number of decimal places.

Some questions:

What software is going to consume the output DBF file?

There is no such thing as "the" (one and only) DBF file format. Do you need dBase III ? dBase 4? 7? Visual FoxPro? etc?

What is the maximum length of text field that you need to write? Do you have non-ASCII text?

Which version of Python?

If your requirements are minimal (dBase III format, no non-ASCII text, text <= 254 bytes long, Python 2.X), then the cookbook recipe that you quoted should do the job.

like image 28
John Machin Avatar answered Oct 24 '22 12:10

John Machin