[R] Open file for reading and writing with APPEND

Noah Silverman noahsilverman at ucla.edu
Wed Sep 14 21:38:56 CEST 2011


Hi,

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.

Any ideas?

Here is what I'm using:


=============================
outfile <- file("logfile.csv", open="r")
x <- readLines(outfile)
lastLine <- x[length(x)]
a <- as.numeric( strsplit(lastLine, " +")[[1]][1] )
b <- as.numeric( strsplit(lastLine, " +")[[1]][2] )
c <- as.numeric( strsplit(lastLine, " +")[[1]][3] )
close(outfile)

outfile <- file("logfile.csv", open="w")


while(1){
	# do a bunch of stuff
	cat(a, b, c, sep=",", "\n",  file=outfile, append=TRUE)
	
}

=========================


--
Noah Silverman
UCLA Department of Statistics
8117 Math Sciences Building #8208
Los Angeles, CA 90095



More information about the R-help mailing list