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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With