6

I am trying to append a line in an already existing .txt file. But my syntax overwrites this file :(

   fileConn <- file( "realization1.txt" )
      write(x =as.character(max(cumsum( rnorm( 10^7)))),
            file = fileConn,
            append = TRUE, sep = " ")


      write(x =as.character(max(cumsum( rnorm( 10^7)))),
            file = fileConn,
            append = TRUE, sep = " ")
   }

   close( fileConn )

Does anybody have any solution to this? Thanks for help!

Marcin
  • 7,834
  • 8
  • 52
  • 99

3 Answers3

5

I believe your difficulty comes from failing to open the file with the proper attributes set.

If you create the connection with fileConn <- file( "realization1.txt" ,open="a") , then all will work as you expect. Basically, so far as I can tell, write (which is a wrapper for cat ) cannot append unless the file connection was opened with "append" allowed.

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
2

You can also use writeLines, which is about 20x faster than write. This makes a big difference if you are appending large character strings.

sink("outfile.txt", append = T)

x <- as.character(max(cumsum( rnorm( 10^7))))
writeLines(x)

sink()
rafa.pereira
  • 13,251
  • 6
  • 71
  • 109
0

I would just use the command write.table

write.table(max(cumsum( rnorm( 10^7))),file="realization1.txt",append=TRUE,row.names=FALSE,col.names=FALSE)

write.table(max(cumsum( rnorm( 10^7))),file="realization1.txt",append=TRUE,row.names=FALSE,col.names=FALSE)

You will find the 2 values in the 'realizaion1.txt' file

Fabio
  • 518
  • 1
  • 4
  • 10