Search code examples
rfor-loopexportoutputwrite.table

How to overwrite existing .txt files after for loop


I am trying to use for loop to remove the initial part of each text and then export the revised text using write.table, but in my folder I noticed the write.table will generate a set of new files instead of replacing the original ones. Can anyone show me how to overwrite existing files?

for(i in 1:length(file.names)){
  text.v <- scan(file.names[i], what="character", encoding = "UTF-8")
  novel.v <- paste(text.v, collapse=" " )
  word.v <- gsub(".*</Header> ","", novel.v)
  write.table(paste(word.v,collapse = " "), paste(file.names[i],".txt",sep=""), row.names=FALSE, col.names=FALSE, quote=FALSE)
}

Solution

  • It seems to me that you are trying to write your files with 'two' extensions, because you read them like filenameWithExtension and than you write them filenameWithExtension.txt. If that's the case, the solution it's just change this paste(file.names[i],".txt",sep="") to this file.names[i].

    In case I'm wrong, you should show us an example of file.name's content.