gmann
gmann

Reputation: 35

Is there any way I can convert CSV files w/o avoid converting already converted files

Hi im absolute novice with google script in general, ive been tweaking around with this script i found from Bulk convert csv files in Google drive to Google Sheets:

function convert() {
      var folder = DriveApp.getFolderById('folder id here');
      var files = folder.getFiles();
      while (files.hasNext()) {
        var file = files.next();
        Drive.Files.copy({}, file.getId(), {convert: true});
      }
    } 

and it works like a charm. the problem is that the this code indiscriminately convert every file in the said folder, including the converted file and source file. so if i run the script for the 2nd i would end up with a new copy of the converted file and another copy of the source file.

is there any way to work around this? i was thinking something along the lines of moving the converted files into a different folder and allow file overwriting to avoid copies.

thank you so much in advance.

Upvotes: 1

Views: 211

Answers (1)

Tanaike
Tanaike

Reputation: 201643

How about this modification?

In this modification, I would like to propose the following workaround.

Workaround:

In this workaround, the mimeType of the source file is checked, and also, the description is given the copied source file. The description is used as the checker whether the file had been copied. By this, when the script is run for the 1st time, the CSV source files are converted to Google Spreadsheet. At that time, the description is added to the source files as copied. And, in the 2nd run, the files with the mimeType of CSV and the description has no value of copied are copied and converted. By this flow, the files which has been copied are not used after 2nd run.

When above workaround is reflected to your script, it becomes as follows.

Sample script:

function convert() {
  var folder = DriveApp.getFolderById('folder id here');
  var files = folder.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    if (file.getMimeType() == MimeType.CSV && file.getDescription() != "copied") {  // Added
      file.setDescription("copied");  // Added
      Drive.Files.copy({}, file.getId(), {convert: true});
    }
  }
}

Note:

  • When you have already used the description of the file, you can also use the property of the file.

  • If you want to copy the source CSV files every run, you can also use the following modified script. In this case, only the mimeType is checked.

      function convert() {
        var folder = DriveApp.getFolderById('folder id here');
        var files = folder.getFiles();
        while (files.hasNext()) {
          var file = files.next();
          if (file.getMimeType() == MimeType.CSV) {  // Added
            Drive.Files.copy({}, file.getId(), {convert: true});
          }
        }
      } 
    

References:

Upvotes: 1

Related Questions