我正在寻找一种方法来防止R在会话期间覆盖文件。通用解决方案更好。
目前,我有一堆被称为safe.save、safe.png、safe.write.table等函数,它们的实现大致如下:
目前,我有一堆被称为safe.save、safe.png、safe.write.table等函数,它们的实现大致如下:
safe.smth <- function(..., file) {
if (file.exists(file))
stop("File exists!")
else
smth(..., file=file)
}
它可以工作,但仅在我控制执行时。如果某些(不是我的)函数创建文件,我无法阻止它覆盖。
另一种方法是在文件上设置只读标志,这也可以防止R覆盖现有文件。但是这也有缺点(例如:您不知道哪些文件需要受到保护)。
或者编写一行代码:
protect <- function(p) if (file.exists(p)) stop("File exsits!") else p
并在提供文件名时始终使用它。
有没有一种方法可以强制会话范围内的这种行为?是否有连接的全局设置?也许只针对某些函数(图形设备,file
创建的连接等)?也许有一些系统特定的解决方案?
以下内容可用作测试用例:
test <- function(i) {
try(write.table(i, "test_001.csv"))
try(writeLines(as.character(i), "test_002.txt"))
try({png("test_003.png");plot(i);dev.off()})
try({pdf("test_004.pdf");plot(i);dev.off()})
try(save(i, file="test_005.RData"))
try({f<-file("test_006.txt", "w");cat(as.character(i), file=f);close(f)})
}
test(1)
magic_incantations() # or magic_incantations(test(2)), etc.
test(2) # should fail on all writes (to test set read-only to files from first call)
set noclobber
只能防止 bash 重定向(例如>
)的覆盖,所以在这里没有运气。 - Marek