首页 > 解决方案 > file.next().setTrashed(true) 无法从谷歌驱动器中删除文件

问题描述

我想在处理后将我的谷歌驱动器文件夹中的文件移动到垃圾箱。在此函数中,我对其进行处理,然后我想将其丢弃,但丢弃行出现错误:Exception: Cannot retrieve the next object: iterator has reached the end. (line 20)

// Import CSV file data into spreadsheet
function importCSV () {
  const folder = DriveApp.getFolderById("xyz");
  const file = folder.getFilesByName("name.csv");
  if (file.hasNext()) {
    const csvString = file.next().getBlob().getDataAsString();
    const csvData = Utilities.parseCsv(csvString);
    const lastRow = csvSheet.getLastRow();
    csvSheet.getRange(lastRow+1,1,csvData.length,csvData[0].length).setValues(csvData);
    file.next().setTrashed(true);// Delete the csv file so next time there aren't name conflicts
  } 
}

标签: google-apps-scriptgoogle-sheets

解决方案


修改点:

  • 在您的脚本中,file是 FileIterator。
  • 在您的 if 语句中,file.next()使用了 2 次。在这种情况下, 1stfile.next()与 2nd 不同file.next()。如果文件名的文件name.csv只存在一个文件,则在file.next()运行 2nd 时会发生错误。我认为这可能是您的问题的原因。
  • 当您要将处理后的文件移动到垃圾箱时,需要使用setTrashed1st file.next()

当以上几点反映到您的脚本时,它变成如下。

修改后的脚本:

function importCSV () {
  const folder = DriveApp.getFolderById("xyz");
  const file = folder.getFilesByName("name.csv");
  if (file.hasNext()) {
    const f = file.next(); // Added
    const csvString = f.getBlob().getDataAsString(); // Modified
    const csvData = Utilities.parseCsv(csvString);
    const lastRow = csvSheet.getLastRow();
    csvSheet.getRange(lastRow+1,1,csvData.length,csvData[0].length).setValues(csvData);
    f.setTrashed(true); // Modified
  }
}

参考:


推荐阅读