我正在遍历.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
}
我宁愿从解压缩程序中捕获错误,跳过该损坏的文件,然后继续执行我的循环。我已经尝试使用
try
和tryCatch
,但是没有运气。有没有一种方法告诉
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 TracebackRerun 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/