【发布时间】:2019-01-15 01:01:06
【问题描述】:
我正在使用 R 为一些批量复制/重命名操作运行脚本。该脚本使用.bat 文件执行,以便在 MS Windows 中使用命令提示符执行。请注意,将运行此程序的目标计算机不允许外部连接(否则为互联网)安装新软件包,因此解决方案应位于 base R 中。
我可以使用cat 将cmets 打印到屏幕上,并且输出显示在脚本运行后生成的.Rout 文件中。每次执行脚本时,.Rout 文件都会被覆盖,我想创建一个单独的日志文件。
以下是相关代码:
if(copy_files){
# tried different modes for the file statement below
log_con <- file(paste(format(Sys.time(), '%d-%b-%Y %H:%M:%S'),
'move duplicates.txt'),
open = 'at')
cat('Parent directory:\t\t' , file = log_con, append= F)
cat(parent_folder , file = log_con, append= T)
cat('\nSubfolder to copy files to:\t ', file = log_con, append= T)
cat(subfolder_old, file = log_con, append= T)
cat('\n\n', file = log_con, append= T)
# copying operations here - omitted for brevity
}
仅使用不带file 和append 参数的cat 语句可以正常工作,但上述代码返回以下错误消息:
> log_con <- file(paste(format(Sys.time(), '%d-%b-%Y %H:%M:%S'), 'move duplicates.txt'), open = 'at')
Error in file(paste(format(Sys.time(), "%d-%b-%Y %H:%M:%S"), "move duplicates.txt"), :
cannot open the connection
In addition: Warning message:
In file(paste(format(Sys.time(), "%d-%b-%Y %H:%M:%S"), "move duplicates.txt"), :
cannot open file '07-Aug-2018 15:50:36 move duplicates.txt': Invalid argument
> cat('Parent directory:\t\t' , file = log_con, append= F)
Error in cat("Parent directory:\t\t", file = log_con, append = F) :
cannot open the connection
In addition: Warning message:
In cat("Parent directory:\t\t", file = log_con, append = F) :
cannot open file '07-Aug-2018 15:48:11 move duplicates.txt': Invalid argument
据我了解,错误源于日志文件一开始不存在并且无法打开连接的事实。
查看文档和How to create periodically send text to a "log file" while printing normal output to console? 的答案似乎表明在第一个cat 语句中包含append = F 应该可以工作。我已经尝试过为file 命令指定不同/没有mode 并具有相同结果的版本。 Add lines to a file 的答案似乎表明相同。我错过了什么吗?
我可以创建一个文件并让 R 每次都在其中附加行,但我希望每次运行脚本时都有一个唯一的日志。
【问题讨论】: