使用 python 将 .dbc 文件转换为 .csv

Luc*_*eca 7 python dbf

我正在编写一个 python 脚本来将.DBC文件(来自 Datasus)转换为.CSV.

我搜索了很多库来帮助我,但没有取得成功。有人知道在此转换任务中可能有用的选项/包吗?

Luc*_*eca 7

我真的不明白为什么有些成员给这个问题给-1,但并没有真正回答它。

好吧,我还没有找到一个好的库来转换.DBC.CSV. 但我可以使用 Python + R 来做到这一点,我在这里分享我是如何实现它的。

下面的 Python 脚本获取 R 路径并执行dbc2csv.R发送三个参数的文件:原始文件路径、转换后的文件路径以及将转换的文件名。

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
Run Code Online (Sandbox Code Playgroud)

下面的 R 脚本dbc2csv.R实际上是要转换的人。

#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)
Run Code Online (Sandbox Code Playgroud)

我们确实知道如果我们只使用 Python 进行转换会更好。但这种方法效果很好。