Home > Software design >  How to append data to file with write function?
How to append data to file with write function?

Time:11-23

I thought that snippet will do the trick:

f <- file("append2me.txt")

write(1:5,  ncolumns = 5, f)
write(6:10, ncolumns = 5, f, append = T)

close(f)

f <- file("append2me.txt")

print(readLines(f))

But the result is:

[1] "6 7 8 9 10"

Why is that?

CodePudding user response:

It is about how we open the file:

f <- file("append2me.txt", open = "a")
write(1:5,  ncolumns = 5, file = f)
write(6:10, ncolumns = 5, file = f)
close(f)

f1 <- file("append2me.txt", open = "r")
readLines(con = f1)
close(f1)
# [1] "1 2 3 4 5"  "6 7 8 9 10"

write is just a wrapper for cat, from cat manuals, see:

append logical. Only used if the argument file is the name of file (and not a connection or "|cmd"). If TRUE output will be appended to file; otherwise, it will overwrite the contents of file.

  • Related