Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R write(append=TRUE) overwrites file contents

Tags:

file-io

append

r

Here's 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), testfile then contains:

world

I expected:

hello
world

The same behavior happens if I use cat() instead of write(). Why? How can I append to files?

like image 236
John Zwinck Avatar asked Jul 24 '14 07:07

John Zwinck


1 Answers

You must open the file for writing:

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

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

If you do not pass 'w', each write call opens and closes the file, and I guess this causes the strange behaviour you observe.

If you want to open an existing file for appending, use

out = file('testfile', 'a')
like image 149
JohnB Avatar answered Nov 08 '22 08:11

JohnB