1
votes

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

1 Answers

1
votes

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.