R语言 循环,分别用于阅读和保存.dbc和.csv文件

nnvyjq4y  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(109)

我试图创建一个循环,读取dbc文件并将其转换为.csv,但当我运行它时,出现错误:dbc 2dbf(file,out)中的错误:解压缩文件时出错:-1.这是什么?

nomes  <- c(
"DNAC2013.dbc", "DNAC2014.dbc", "DNAC2015.dbc", "DNAC2016.dbc", "DNAC2017.dbc", "DNAC2018.dbc", "DNAC2019.dbc", "DNAC2020.dbc", "DNAC2021.dbc",
"DNAL2013.dbc", "DNAL2014.dbc", "DNAL2015.dbc", "DNAL2016.dbc", "DNAL2017.dbc", "DNAL2018.dbc", "DNAL2019.dbc", "DNAL2020.dbc", "DNAL2021.dbc",
"DNAM2013.dbc", "DNAM2014.dbc", "DNAM2015.dbc", "DNAM2016.dbc", "DNAM2017.dbc", "DNAM2018.dbc", "DNAM2019.dbc", "DNAM2020.dbc", "DNAM2021.dbc",
"DNAP2013.dbc", "DNAP2014.dbc", "DNAP2015.dbc", "DNAP2016.dbc", "DNAP2017.dbc", "DNAP2018.dbc", "DNAP2019.dbc", "DNAP2020.dbc", "DNAP2021.dbc",
....
)

# Directory where the files are located
diretorio <- "C:/Users/dossa/Downloads/arquivo (1)/vivos/"

# Loop to read and save files
for (nome in nomes) {
  caminho <- paste0(diretorio, nome)
  x <- read.dbc(caminho)
  
  # Remove the .DBC or .dbc extension and add .csv
  nome_csv <- gsub("\\.dbc$", ".csv", nome)
  
  # Define the path to save with the .csv extension
  caminho_csv <- paste(diretorio, nome_csv, sep = "/")
  
  # Save the file as CSV
  write.csv(x, file = caminho_csv)
}
z31licg0

z31licg01#

这不是一个完整的答案,但请尝试以下代码,以查看哪些文件出错,哪些文件作为csv文件被读取和写入。对read.dbc的调用是在tryCatch语句中进行的,错误以列表的形式返回。该列表在for循环后进行测试。
注意,我已经从diretorio中删除了最后一个"/"。这是因为我使用file.path从它们的目录和基本名称中组装文件名。

diretorio <- "C:/Users/dossa/Downloads/arquivo (1)/vivos"

# list to hold read.dbc errors, if any
err_list <- vector("list", length(nomes)) |> setNames(nomes)
# Loop to read and save files
for(nome in nomes) {
  caminho <- file.path(diretorio, nome)
  x <- tryCatch(read.dbc(caminho), error = function(e) e)
  
  if(!inherits(x, "error")) {
    # Remove the .DBC or .dbc extension and add .csv
    nome_csv <- tools::file_path_sans_ext(nome) |> paste0(".csv")
    
    # Define the path to save with the .csv extension
    caminho_csv <- file.path(diretorio, nome_csv)
    
    # Save the file as CSV
    write.csv(x, file = caminho_csv)
    err_list[[nome]] <- "ok"
  } else err_list[[nome]] <- e
}

err <- sapply(err_list, inherits, "error")
nomes[err]

相关问题