如何预先添加到文件(添加在顶部) [英] How to prepend to a file (add at the top)
问题描述
假设你有一个文件
sink(example.txt)
$ b
data.frame runif(10),b = runif(10),c = runif(10))
sink()
,并希望添加一些标题信息,例如
/ * created on 31.3.2011 * /
/ * author * /
/ *其他冗余信息* /
添加这个标题?手动执行它似乎微不足道。命中几个进入,复制/粘贴或写信息,你完成了。当然,在R中,我可以读取
example.txt
,创建example2.txt
,添加头信息,然后example.txt
。
我想知道是否有另一种方式从顶部附加文件。其他解决方案(从c ++或Java ...)也欢迎(我很好奇其他语言如何解决这个问题)。
解决方案在R中没有必要使用额外的文件。您可以执行:
writeLines(c(header,readLines(File)),File)
然而,使用linux shell似乎是最优的解决方案,因为R对于执行文件读写并不出名。
示例:
<$> c $ c> Lines < - c(
第一行,
第二行,
第三行)
文件< - test.txt
header< - 一行\另一行\\\
More行\\\
\\\
writeLines(Lines,File)
readLines(File)
writeLines(c(header,readLines(File)),File)
readLines(File)
unlink(File)
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
, createexample2.txt
, add header information and thenexample.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屋!