1

I would like to replace a csv file that contains one value at cell A1 with a new csv file that contains again one value at cell A1, but a different value. The following code successfuly creates what I want, but it does not replace the current csv file, it just creates new ones and I end up with many files in the google drive. What can I do to just replace it? Thanks a lot

function replace() {
      var str = "test";
      var folder = DriveApp.getFolderById("folderID");
      var fileName = "add-list.csv";
      var csvFile = str;
      var file = folder.getFilesByName(fileName)
      
     folder.createFile(fileName, csvFile);

}

1 Answer 1

1

You are very close. Before you replace the target csv file, you need to see whether it exists or not.

function replace() {
      var str = "test";
      var folder = DriveApp.getFolderById("folderId");
      var fileName = "add-list.csv";
      var csvFile = str;
      var file = folder.getFilesByName(fileName)
      
      if (file.hasNext()){
     file.next().setTrashed(true) }
     folder.createFile(fileName, csvFile);
    
    }

Explanation:

if (file.hasNext()){
         file.next().setTrashed(true) }
         folder.createFile(fileName, csvFile);

This will check if the file exists. If it does, then it will replace it, otherwise it will create a new one.

Sign up to request clarification or add additional context in comments.

1 Comment

As another method, how about adding the modification from folder.createFile(fileName, csvFile) to if (file.hasNext()) file.next().setContent(str), if OP needs the revisions?

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.