在向其中添加新数据时无法重新打开文件连接

时间:2015-08-19 05:37:32

标签: r

我想保留一个日志:

logcon <- file("log.txt", open="w+")

for(i in 1:10){
  writeLines(text=as.character(Sys.time()), con=logcon, sep="\n")
  Sys.sleep(3)
}

close(logcon)

open(logcon)

问题

  1. 每次创建连接时,它都会创建一个覆盖旧文件的新文件。如何将新时间日志添加到同一文件中?

  2. 在关闭连接之前,log.txt什么也没显示。连接关闭后,所有日志都会显示

  3. 在追加新数据时,open(logcon)会返回error > open(logcon) Error in open.connection(logcon) : invalid connection

  4. 我试过

     for(i in 1:10){
       write.table(as.character(Sys.time()),"log.txt", append = TRUE, col.names = FALSE)
       Sys.sleep(3)
    }
    

    一切都运作良好。

1 个答案:

答案 0 :(得分:0)

就追加数据而言,您需要在打开连接时使用其他模式:

logcon<-file("log.txt", open="a")

对于这些行,你总是可以尝试使用sink来重定向输出而不是writeLines,例如。

sink(logcon) # direct to your file connection
as.character(Sys.time()) # or whatever you want to push out. remember cat here
sink() # change your output back to terminal
相关问题