R write (append = TRUE) overwrites the contents of the file

Here is my R code:

out = file('testfile') write('hello', file=out, append=T) write('world', file=out, append=T) close(out) 

When I run this (using R 3.1.0), the test file contains:

 world 

I expected:

 hello world 

The same thing happens if I use cat() instead of write() . What for? How can I add files?

+7
append file-io r
source share
2 answers

You must open the file for writing:

 out = file('testfile', 'w') ... 

When R opens (or does not open) connections automatically, it is a little complicated, but explained in the help ( ?file ).

If you don't pass 'w' , each write call opens and closes the file, and I assume this causes the weird behavior you observe.

If you want to open an existing file to add, use

 out = file('testfile', 'a') 
+11
source share

The key is on the help page for cat (for which write is a wrapper):

append boolean. Used only if the argument file is the name of the file (not the connection or "| cmd"). If TRUE output will be added to the file; otherwise, it will overwrite the contents of the file.

When using connections, you must establish a connection to open to add, for example:

 file('testfile', open="a") 
+3
source share

All Articles