我有很多大的文本文件,我想在开头添加一行。我看到这里已经有人问过这个了。但是,这需要读取整个文本文件并将其附加到单行中。有更好(更快)的方法吗?
我在Windows7上测试了它,它可以工作。从本质上讲,您使用shell
函数并在窗口cmd
上执行所有操作,这非常快。
write_beginning <- function(text, file){
#write your text to a temp file i.e. temp.txt
write(text, file='temp.txt')
#print temp.txt to a new file
shell(paste('type temp.txt >' , 'new.txt'))
#append your file to new.txt
shell(paste('type', file, '>> new.txt'))
#remove temp.txt - I use capture output to get rid of the
#annoying TRUE printed by file.remove
dump <- capture.output(file.remove('temp.txt'))
#uncomment the last line below to rename new.txt with the name of your file
#and essentially modify your old file
#dump <- capture.output(file.rename('new.txt', file))
}
#assuming your file is test.txt and you want to add 'hello' at the beginning just do:
write_beginning('hello', 'test.txt')
在linux上,您只需要找到相应的命令就可以将文件发送到另一个命令(我真的认为您需要在linux上用cat
替换type
,但我现在无法测试)。
您可以在Linux发行版上使用system()函数:
system('cp file.txt temp.txt; echo " " > file.txt; cat temp.txt >> file.txt; rm temp.txt')