LoginSignup
5
4

More than 3 years have passed since last update.

【Godot】CSVファイルの読み込み方法

Posted at

概要

この記事では Godot Engine で CSVファイルを読み込む方法について解説します。

CSVファイルの作成

今回は以下のデータを扱うとします。

data.txt
hero,100,20
fighter,150,0
magician,50,80

ファイル名は data.txt とします。
拡張子は .csv としたいところですが、 .csv は翻訳データと扱われて実行時にエラーメッセージが表示される(実行はできるのが今後問題が起きるかも……?)ので、念のため .txt としました。

ファイル読み込み

ファイル読み込みは File オブジェクトを使うことで簡単にロードできます。

extends Node2D

func _ready():

  # ファイルオブジェクト作成
  var f = File.new()

  # "data.txt" ファイルを開く
  f.open("res://data.txt", File.READ)

  # テキストの内容を出力
  print(f.get_as_text())

  # ファイルを閉じる
  f.close()

CSVを1行ずつ読み込む

Fileオブジェクトの get_csv_line() を使用すると、指定の区切り文字(デフォルトは ",")で区切った配列を返してくれます。


extends Node2D

func _ready():

    # ファイルオブジェクト作成
    var f = File.new()

    # "data.txt" ファイルを開く
    f.open("res://data.txt", File.READ)

    # CSVを1行ずつ読み込む
    var line = f.get_csv_line()
    while line.size() >= 3: # 横方向の項目数が足りない場合は終了
        print("name: %s"%line[0])
        print("hp:   %s"%line[1])
        print("mp:   %s"%line[2])
        line = f.get_csv_line()

    # ファイルを閉じる
    f.close()

実行結果

name: hero
hp:   100
mp:   20
name: fighter
hp:   150
mp:   0
name: magician
hp:   50
mp:   80

get_line() で1行ずつ読み込んで、split() で分割しても良いですが、少し楽できます。

空行を読み飛ばす判定による実装

なお、ファイル(データ)の終了を File.eof_reached() で判定する方法もありますが、その場合は最後の行が空行(改行文字だけ)かどうかを判定する処理が必要となります。

空行を読み飛ばす判定による実装
extends Node2D

func _ready():

    # ファイルオブジェクト作成
    var f = File.new()

    # "data.txt" ファイルを開く
    f.open("res://data.txt", File.READ)

    # CSVを1行ずつ読み込む
    while f.eof_reached() == false: # ファイルの終端チェック
        var line = f.get_csv_line()
        if line[0] == "":
            continue # 空行を読み飛ばす

        print("name: %s"%line[0])
        print("hp:   %s"%line[1])
        print("mp:   %s"%line[2])

    # ファイルを閉じる
    f.close()

参考

5
4
0

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
5
4