我想安全地测试一个文件(例如,名为
test.docx
)是否使用 R
打开。
这个 answer 提出了一个解决方案,但相关评论抱怨它损坏了文件。我也发现当我在
docx
上使用它时,它会损坏文件并导致空白 test.docx
。
使用
docx
(称为 rmarkdown
)生成示例 test.Rmd
文件的代码:
---
title: "test"
output:
officedown::rdocx_document:
---
# heading 1
# heading 2
渲染调用:
library(bookdown)
library(officedown)
library(officer)
rmarkdown::render('test.Rmd',
output_format = 'rdocx_document')
使用建议的解决方案测试是否打开:
file.opened <- function(path) {
suppressWarnings(
"try-error" %in% class(
try(file(path,
open = "w"),
silent = TRUE
)
)
)
}
file.opened("test.docx")
# [1] FALSE
它正确返回
FALSE
,因为我还没有打开该文件,但该文件现已被编辑并且是空白的(文件大小减小到0
)。
有什么安全的方法来测试它是否打开?
谢谢
这就是我编写这个函数的方式:
is_file_open <- function(path, mode = "r+b") {
tryCatch(
{
con <- suppressWarnings(file(path, open = mode))
on.exit(close(con))
FALSE
},
error = function(e) TRUE
)
}
这会给出正确的输出,并且不会删除文件的内容:
# With the file open in MS Word
is_file_open("test.docx")
# [1] TRUE
# With the file not open
is_file_open("test.docx")
# [1] FALSE