How to prepend to a file (add at the top)

后端 未结 8 985
逝去的感伤
逝去的感伤 2020-12-20 13:12

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 hea

8条回答
  •  無奈伤痛
    2020-12-20 13:23

    In R, following the original question:

    df <- data.frame(a = runif(10), b = runif(10), c = runif(10))
    txt <- "# created on 31.3.2011 \n# author \n# other redundant information"
    write(txt, file = "example.txt") 
    write.table(df, file = "example.txt", row.names = FALSE, append = TRUE)
    

    The solution provided by Joris Meys does not work properly, overwrites the content, not appending the header to the Lines. A working version would be:

    Lines <- c("First line", "Second line", "Third line")
    File <- "test.txt"
    header <- "A line \nAnother line \nMore line \n\n"
    writeLines(Lines, File)
    txt <- c(header, readLines(File)) 
    writeLines(txt, File) # Option1
    readLines(File) 
    

    Instead of writeLines we could use too:

    write(txt, File) # Option 2
    cat(txt, sep="\n", File) # Option 3
    

提交回复
热议问题