我希望Google脚本变量数据作为文本文件存储到Google云端硬盘中,并通过Google脚本更新该文本文件规则!
以下代码创建一个文本文件并在其上写入数据。我想知道以后如何更新文本文件?
function createTextFile()
{
name="testFile.txt";
name2="testFolder";
var content = "this is text data to be written in text file";
var dir = DriveApp.getFoldersByName(name2).next()
var file = dir.createFile(name, content);
}
答案 0 :(得分:5)
更新如果文件存在,则覆盖内容。
function saveData(folder, fileName, contents) {
var filename = "testFile.txt";
var children = folder.getFilesByName(filename);
var file = null;
if (children.hasNext()) {
file = children.next();
file.setContent(contents);
} else {
file = folder.createFile(filename, contents);
}
}
function test() {
var folders = DriveApp.getFoldersByName("testFolder");
if (folders.hasNext()) {
var folder = folders.next();
saveData(folder, "testfile.txt", "HelloWorld");
saveData(folder, "testfile.txt", "Welcome");
}
}
答案 1 :(得分:0)
以防万一三年后仍然有人对此感兴趣...:)
假设内容为文本,以下内容将创建或追加:
function createOrAppendFile() {
var fileName="myfile";
var folderName="myfolder";
var content = "this is text data to be written in text file";
// get list of folders with matching name
var folderList = DriveApp.getFoldersByName(folderName);
if (folderList.hasNext()) {
// found matching folder
var folder = folderList.next();
// search for files with matching name
var fileList = folder.getFilesByName(fileName);
if (fileList.hasNext()) {
// found matching file - append text
var file = fileList.next();
var combinedContent = file.getBlob().getDataAsString() + content;
file.setContent(combinedContent);
}
else {
// file not found - create new
folder.createFile(fileName, content);
}
}
}
总而言之,由于似乎没有附加功能,因此您只需读取现有文件内容,添加新内容,然后(覆盖)组合的内容回文件中即可。
* tip-在旧内容和新内容之间添加“ \ n”以用于新的行分隔符