1

My google apps script imports a csv file [test.csv] into a new tab, manipulates some values, then saves the manipulated tab as a csv file [test.csv]. When it saves the new version, it simply makes another copy [test(1).csv]. I wish instead to overwrite the previous file (or delete the old one then export/write the new version.) Help please?

I am using reference code from the Interacting With Docs List Tutorial

2 Answers 2

8

I know this is an old question, but much of the information in the accepted answer has been deprecated by Google since then. DocsList is gone, as are the clear() and append() methods on a file object.

I use the following function to create or overwrite a file:

// Creates or replaces an existing file
function updateFile (folder, filename, data) {
  try {
    // filename is unique, so we can get first element of iterator
    var file = folder.getFilesByName(filename).next()
    file.setContent(data)
  } catch(e) {
    folder.createFile(filename, data)
  }
}

For reference, here's some code for doing the same for a folder. It assumes we're operating in the parent folder of the current sheet and want a folder object for a new or existing folder there.

// Get folder under current folder. Create it if it does not exist
function getOrCreateFolder(csvFolderName) {
  var thisFileId = SpreadsheetApp.getActive().getId();
  var thisFile = DriveApp.getFileById(thisFileId);
  var parentFolder = thisFile.getParents().next();
  try {
    // csvFolderName is unique, so we can get first element of iterator
    var folder = parentFolder.getFoldersByName(csvFolderName).next();
    // asking for the folder's name ensures we get an error if the
    // folder doesn't exist. I've found I don't necessarily catch
    // an error from getFoldersByName if csvFolderName doesn't exist.
    fname = folder.getName()
  } catch(e) {
    var folder = parentFolder.createFolder(csvFolderName);
  }
  return folder
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this but I can confirm that it doesn't work for pdf files. I suspect replacing the content of these files isn't supported. I haven't checked whether it supports google doc overwrites though.
0

You could do DocsList.find(fileName) which gives you a list of files that have that name. If file names are unique, then you can just do var file = DocsList.find(fileName)[0].


If you are a Google Apps user, you can use file.clear() to remove all the contents of the old file, and then file.append() to insert all of the new contents.


Otherwise, you will have to file.setTrashed(true) and then DocsList.createFile() to make the new one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.