WetlabStudent
WetlabStudent

Reputation: 2606

How to append to an existing file in R without overwriting it?

I would like to write to a file and then append it several times in a loop (on a windows machine). After each time I append it, I want to close the connection because I want the file to sink to a dropbox account so I can open it on other computers, while the code is running, to check the log file's status (note this condition makes this question different from any question asked on SO about sink, writeLines, write, cat, etc). I've tried

#set up writing
  logFile = file("log_file.txt")
  write("This is a log file for ... ", file=logFile, append=FALSE)

for(i in 1:10){
    write(i, file=logFile, append=TRUE)
}

I've also tried sink(file=logFile,append=TRUE); print(i); sink(); in the loop and also cat. Neither option works. The file only displays i=10, the last iteration of the loop. I noticed the following sentence in the documentation for write.

"if TRUE the data x are appended to the connection."

Does the above mean that it won't append to an existing file.

Upvotes: 8

Views: 22244

Answers (2)

Vincent
Vincent

Reputation: 5249

The following seems to work with cat because it doesn't need a file connection:

#set up writing
logFile = "log_file.txt"
cat("This is a log file for ... ", file=logFile, append=FALSE, sep = "\n")

for(i in 1:10){
  cat(i, file=logFile, append=TRUE, sep = "\n")
}

The output would look like so it does append each value:

This is a log file for ... 
1
2
3
4
5
6
7
8
9
10

Which I think is what you want. If you are on a mac or using linux you can keep track of progress in the file using:

tail -f log_file.txt 

I am not sure how this would work with dropbox however. Can you login to the computer running the code (e.g., on mac or linux)?

Upvotes: 11

wespiserA
wespiserA

Reputation: 3168

what about explicitly closing the file after every iteration?

#set up writing
  file.text <- "log_file.txt"
  logFile = file(file.txt)
  write("This is a log file for ... ", file=logFile, append=FALSE)
  close(logFile)
for(i in 1:10){
    logFile <- file(file.text)
    write(i, file=logFile, append=TRUE)
    close(logFile)
}

Upvotes: 0

Related Questions