Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用file和cat在Base R中创建日志文件_R_Logging_Cat - Fatal编程技术网

使用file和cat在Base R中创建日志文件

使用file和cat在Base R中创建日志文件,r,logging,cat,R,Logging,Cat,我正在使用R运行一些批复制/重命名操作的脚本。该脚本是使用MS Windows中使用命令提示符执行的.bat文件执行的。请注意,运行此操作的目标计算机不允许外部连接(internet或其他)安装新软件包,因此解决方案应位于base R中 我可以使用cat将注释打印到屏幕上,输出显示在脚本运行后生成的.Rout文件中。每次执行脚本时,.Rout文件都会被覆盖,我想创建一个单独的日志文件 以下是相关的代码: if(copy_files){ # tried different modes for

我正在使用R运行一些批复制/重命名操作的脚本。该脚本是使用MS Windows中使用命令提示符执行的
.bat
文件执行的。请注意,运行此操作的目标计算机不允许外部连接(internet或其他)安装新软件包,因此解决方案应位于base R

我可以使用
cat
将注释打印到屏幕上,输出显示在脚本运行后生成的
.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
}
据我所知,错误源于日志文件在开始时不存在,并且无法打开连接

查看文档和的答案似乎表明,在第一个
cat
语句中包含
append=F
,应该是可行的。我尝试过为
文件
命令指定不同/no
模式
的版本,结果相同。这些问题的答案似乎都是这样的。我错过什么了吗


我可以创建一个文件,每次都有R个附加行,但我希望每次运行脚本时都有一个唯一的日志

解决这个问题的一种方法是使用sink,在代码开始时将放入sink(“R\u code.log”)整个过程完成后,将放入sink()代码的最后一行。我希望这能解决您的问题,如果您想动态命名它,请在sink函数中使用paste0

> 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