r - 从tar捕获错误并继续处理

标签 r error-handling

我正在遍历.tar.gz文件列表,解压缩它们并对其进行一些分析。到现在为止还挺好。问题是,当某些文件损坏时,untar引发错误并且处理停止。

我的代码是这样的:

f <- dir(path.to.files, pattern=".tar.gz")
for(k in 1:length(f)){
  # make sure the temporary dir is empty
  file.remove(dir(path = tempdir(), full.names = TRUE)
  untar(f[k], exdir = tempdir())
  # do some analisys with the extracted files
}

我宁愿从解压缩程序中捕获错误,跳过该损坏的文件,然后继续执行我的循环。我已经尝试使用trytryCatch,但是没有运气。

有没有一种方法告诉untar发出警告而不是错误?

最佳答案

您可以通过将next添加到tryCatch的finally参数来继续循环。考虑以下示例。循环从1到3运行,并打印迭代值。当值等于2时,R尝试解压缩文件“untitled-3.synctex1.gz”,该文件在我当前的工作目录中不存在

for(i in 1:3) {
  print(i)
  if(i == 2) tryCatch(untar("untitled-3.synctex1.gz"), finally=next)
}

[1] 1
[1] 2
Show Traceback

Rerun with Debug Error in gzfile(path.expand(tarfile), "rb") : cannot open the connection In addition: Warning message:
In gzfile(path.expand(tarfile), "rb") : cannot open compressed file 'untitled-3.synctex1.gz', probable reason 'No such file or directory'
[1] 3



我们看到错误消息和警告,但是循环继续到下一次迭代并打印第三个值。

关于r - 从tar捕获错误并继续处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411887/

相关文章:

r - 添加 geom_rect 时对象消失

r - 我们如何将整数拆分为 R 中其组成数字的向量

r - R-bin木;如果观察次数为N,成功的概率如何定义?

r - R 中 xtabs() 表内的数学运算

r - 在R中带有警告的函数中抑制,记录和返回值

android - Kotlin 协程 - 优雅地处理来自挂起函数的错误

error-handling - 在 Lua 中解析错误字符串

android - 在Flutter应用程序中获取图片流错误

asp-classic - 如何忽略从ASP调用的SQL Server 2000过程中嵌套存储过程中的错误

python - python错误处理中的图像下载