[R] Open file for reading and writing with APPEND
noahsilverman at ucla.edu
Wed Sep 14 21:38:56 CEST 2011
I want to keep a running file of some statistics generated by a running process. Occasionally the process will be restarted.
On restart, I'd like to read the last line of the log file to set some variables to their last state, and then continue to append values to that same file.
I can't seem to get the appending part to work. I can read values form the file, but then upon the first write, the file is overwritten with the new values, so I lose my entire history.
Here is what I'm using:
outfile <- file("logfile.csv", open="r")
x <- readLines(outfile)
lastLine <- x[length(x)]
a <- as.numeric( strsplit(lastLine, " +")[] )
b <- as.numeric( strsplit(lastLine, " +")[] )
c <- as.numeric( strsplit(lastLine, " +")[] )
outfile <- file("logfile.csv", open="w")
# do a bunch of stuff
cat(a, b, c, sep=",", "\n", file=outfile, append=TRUE)
UCLA Department of Statistics
8117 Math Sciences Building #8208
Los Angeles, CA 90095
More information about the R-help