Search code examples
pythondbf

Convert .dbc files into .csv with python


I'm writing a python script to convert .DBC files (from Datasus) into .CSV.

I've searched a lot some libs to help me but didn't get success with any of them. Do someone know an option/package which could be useful in this conversion task?


Solution

  • I really don't understand why some members give -1 to the question, but don't really answer it.

    Well, I've not found out a good lib to convert .DBC to .CSV. But I could do it using Python + R and I'm sharing here how I achieved it.

    The Python script below gets R path and executes the dbc2csv.R file sending three args: the raw file path, converted file path, and the file name that will be converted.

    import subprocess
    import commands
    
    
    def dbc2csv(raw_filename):
    dbc2csv_path = "/path/to/script/dbc2csv.R " + raw_files_dir + " " + converted_files_dir + " " + raw_filename
    
    try:
        r_script_path = commands.getstatusoutput('which Rscript')[1]
        subprocess.call(r_script_path + " --vanilla " + dbc2csv_path, shell=True)
        return True
    except:
        print("(Rscript) Error converting file: " + raw_filename)
    
    return False
    

    The R script dbc2csv.R bellow is actually who will convert.

    #install.packages("read.dbc") You need this package
    library("read.dbc")
    
    
    dbc2dbf <- function(rawDir, convertedDir, file) {
        # reads dbc file
        x <- read.dbc(paste(rawDir, file, sep=""))
        # write it to csv
        write.csv(x, file=paste(convertedDir, file, ".csv", sep=""))
    }
    
    args = commandArgs(trailingOnly=TRUE)
    try(dbc2dbf(args[1], args[2], args[3]), TRUE)
    

    We do know it would be better if we could convert using just Python. But this approach will work fine.