google-apps-script - 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
}
}
解决方案
修改点:
- 在您的脚本中,
file
是 FileIterator。 - 在您的 if 语句中,
file.next()
使用了 2 次。在这种情况下, 1stfile.next()
与 2nd 不同file.next()
。如果文件名的文件name.csv
只存在一个文件,则在file.next()
运行 2nd 时会发生错误。我认为这可能是您的问题的原因。 - 当您要将处理后的文件移动到垃圾箱时,需要使用
setTrashed
1stfile.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
}
}
参考:
推荐阅读
- android - 在 Xamarin.Forms 中暂停后台服务
- javascript - 文件上传问题;永远不会调用 XMLHttpRequest (XHR) 并且上传卡在 100%
- swift - Swift:如何使用 Timer 每分钟运行一次 func 以防止垃圾评论?
- python - 获取与单词不同的单词的随机排列
- node.js - 我的全栈应用程序不会同时运行 NodeJS 和 React
- python - 返回值 none 斐波那契数列
- python - 从一个 df 获取值并存储到另一个 df 并同时将值分配给每一行的新列名
- javascript - 如何根据脚本的比率重新计算列之间的值?
- java - Java-Android okhttpclient 发布请求超时
- c# - 视图模型问题