Home > Back-end >  Google App script: Overwrite existing csv file. Not create a copy using createFile
Google App script: Overwrite existing csv file. Not create a copy using createFile

Time:11-26

Hi I've got this Google App script that needs to overwrite a file. At the moment it creates a copy. Is there a line or two that can check if it exists,then delete? Or is there an alternative to createFile that overwrites?

DriveApp.getFolderById(fold).createFile(file.getName() '-' sheet '.csv', csv);

Many thanks for looking!

CodePudding user response:

Filenames are not unique on Google Drive - the uniqueness of files is determined by their ID. Whereas on a regular file system, creating a file with a similar filename would erase the old file, in this case you are creating a new unique file every time.

As far as I know, the easiest way would the be to move the existing file to the trash. You can keep you existing script but add to it. Assuming your file will always exist, this should work:

const folder = DriveApp.getFolderById(fold);
folder.getFilesByName(file.getName() '-' sheet '.csv').next().setTrashed(true);
folder.createFile(file.getName() '-' sheet '.csv', csv);

If you are unsure that a file with that name will exist, or if there might be multiple files with that name, you will have to iterate through all them:

const folder = DriveApp.getFolderById(fold);
const files = folder.getFilesByName(file.getName() '-' sheet '.csv');
while(files.hasNext()){
   let f = files.next();
   f.setTrashed(true);
}

folder.createFile(file.getName() '-' sheet '.csv', csv);

I haven't tested this code, but it should be pretty close to what you need.

  • Related