pietrodito
pietrodito

Reputation: 2100

How to append data to file with write function?

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?

Upvotes: 2

Views: 51

Answers (1)

zx8754
zx8754

Reputation: 56259

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.

Upvotes: 1

Related Questions