how to update google drive text file via google script?

Viewed 13426

I want Google script variable data into Google drive as text file and update that text file regulatory via Google script!

The following code creates a text file and writes the data on it.I wonder how i can update the text file later ?

function createTextFile()
{

  name="testFile.txt";
  name2="testFolder";

  var content = "this is text data to be written in text file";

var dir = DriveApp.getFoldersByName(name2).next()
var file = dir.createFile(name, content);
}
2 Answers

Just in case anyone's still interested 3 years later... :)

The following will create or append, assuming content is text:

function createOrAppendFile() {
  var fileName="myfile";
  var folderName="myfolder";

  var content = "this is text data to be written in text file";

  // get list of folders with matching name
  var folderList = DriveApp.getFoldersByName(folderName);  
  if (folderList.hasNext()) {
    // found matching folder
    var folder = folderList.next();

    // search for files with matching name
    var fileList = folder.getFilesByName(fileName);

    if (fileList.hasNext()) {
      // found matching file - append text
      var file = fileList.next();
      var combinedContent = file.getBlob().getDataAsString() + content;
      file.setContent(combinedContent);
    }
    else {
      // file not found - create new
      folder.createFile(fileName, content);
    }
  }
}

In summary, as there appears to be no append function, you instead simply read the existing file contents, add the new content, then (over)write the combined content back to the file.

*tip - add a "\n" between the old and new content for a new line separator

Related