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.
To append text to a file means adding text to the end of a file without overwriting the file content.
The "a" mode allows you to open a file to append some content to it. And we want to add a new line to it, we can open it using the "a" mode (append) and then, call the write() method, passing the content that we want to append as argument.
Using cat() to Write Lines to Text FileUse append=TRUE to append lines to the existing text file.
Appending a File refers to a process that involves adding new data elements to an existing database. An example of a common file append (or data append) would be the enhancement of a company's customer files. Companies often collect basic information on their clients such as phone numbers, emails, or addresses.
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)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With