LoginSignup
22

More than 3 years have passed since last update.

GASでテキストファイルの内容を読み取る

Last updated at Posted at 2018-03-10

なんでやろうと思ったか

Google Diveの同期を使ってローカル環境から細かな設定ができないかなと思ったから。

プレーンテキストファイルに設定を書き込む

Goole謹製ソフトによる同期

GoogleAppsScript (GAS)に設定の反映

みたいなことを想定しています。

GASでの読み込みコード

ルートフォルダ上にある'test.txt'の内容を読み取ります。
.getRootFolder()の部分は読み取りたいテキストファイルのあるフォルダを指定してください。
例えば

getFolderById('test.txtのあるフォルダid')

Windowsを想定しているためsjisで読み取ってますが、環境によって調整してください。あと.getFilesByName()を使っているため同じ名前のファイルがあるとうまく動きません。

function test () {
  var contents = DriveApp.getRootFolder()
.getFilesByName('test.txt')
.next()
.getBlob()
.getDataAsString("sjis");
  Logger.log(contents);
}

以下を末尾に加えると改行ごとに分けて配列にすることができます。

.split(/[\s]+/)

追記 2019-11-04

JSON版を載せておきます。変数に名前をつけれるので扱いやすいと思います。

function getDataFromMyTextFile() {
  const contents = DriveApp.getRootFolder()
  .getFilesByName('test.txt')
  .next()
  .getBlob()
  .getDataAsString("utf-8")
  .replace(/\r?\n/g, ''); //改行削除

  return JSON.parse(contents);
}

/*text.txt
{ 
"num" : 1,
"test": "hoge",
"arr" : [1,3,4],
"script1" : {"a":1, "b":2, "c":3},
"script2" : {"a":6, "b":7, "c":9}
}
*/
function test3() {
  const data = getDataFromMyTextFile();

  Logger.log(data.num)        // 1
  Logger.log(typeof data.num) // number
  Logger.log(data.test)       // hoge
  Logger.log(data.arr[2])     // 4.0
  Logger.log(data.script1.a + data.script2.a) // 7.0
}

参考資料

第36回.フォルダとファイルを扱う(DriveApp)
https://excel-ubara.com/apps_script1/GAS036.html

Google Apps Script
https://developers.google.com/apps-script/reference/drive/drive-app

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22