Finding a .txt file on Google Drive by name and ge

2019-08-19 12:12发布

问题:

I want to find text files by their name and then get their contents and make them into a var.

I have tried to find the file by its name, but it doesn't seem to work. I'm clueless as to how to find the file contents though.

My code to find the file:

function testThing() { 
    var findquestions = DriveApp.getFilesByName('tempquestions.txt')
Logger.log(findquestions)
}

I want it to log what it found, but the output is nothing but: "FileIterator". I don't know what that means.

回答1:

As you can see in the documentation, .getFilesByName return fileiterator. What's a file iterator? The documentation states

An iterator that allows scripts to iterate over a potentially large collection of files

There may be large amount of files with the same name. This iterator provides access to all those files.

What methods provide access to file from fileIterator? This method does.

How to get contents of such file? Get blob from file and getDataAsString from blob

Logger.log(DriveApp
    .getFilesByName('tempquestions.txt') //fileIterator
    .next() //file(first file with that name)
    .getBlob() //blob
    .getDataAsString() //string
)