Imagine you have a file
sink("example.txt")
data.frame(a = runif(10), b = runif(10), c = runif(10))
sink()
and would want to add some header information, like
/* created on 31.3.2011 */
/* author */
/* other redundant information */
How would I add this "header"? Doing it manually seems trivial. Hit a few Enters, copy/paste or write information and you're done. Of course, in R, I could read in example.txt
, create example2.txt
, add header information and then example.txt
.
I was wondering if there's another way of appending files from the "top". Other solutions (from c++ or Java...) also welcome (I'm curious how other languages approach this problem).
in R there is no need to work with an extra file. You can just do :
writeLines(c(header,readLines(File)),File)
Yet, using the linux shell seems the most optimal solution, as R is not famous for performant file reading and writing. Especially not since you have to read in the complete file first.
Example :
Lines <- c(
"First line",
"Second line",
"Third line")
File <- "test.txt"
header <- "A line \nAnother line \nMore line \n\n"
writeLines(Lines,File)
readLines(File)
writeLines(c(header,readLines(File)),File)
readLines(File)
unlink(File)
It is totally easy in the linux shell:
echo 'your additional header here' >> tempfile
cat example.tst >> tempfile
mv tempfile example
rm tempfile
In any language there is ultimately only one solution. And that is to overwrite the whole file:
contents = readAllOf("example.txt")
overwrite("example.txt", header + contents )
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