+2 votes

Godot has a resource type named TextFile. It has no docs but i want to read the content of a TextFile in code. Is this possible?

And if you can not manipulate it with code: Why?

in Engine by (28 points)

1 Answer

+1 vote

I really wonder what this TextFile for if it has no property Oo
I would have assumed you could use this import for .txt files in your project, but it's still completely useless. Nothing is exposed: https://github.com/godotengine/godot/blob/master/scene/resources/text_file.cpp
So I think this resource was created just to allow the Godot Editor to open files as plain text in the script editor, so it's maybe not intended for use in a game: https://github.com/godotengine/godot/pull/21022

Anyways, you can load a file as text using a function like this:

func load_text_file(path):
    var f = File.new()
    var err = f.open(path, File.READ)
    if err != OK:
        printerr("Could not open file, error code ", err)
        return ""
    var text = f.get_as_text()
    f.close()
    return text


func save_text_file(text, path):
    var f = File.new()
    var err = f.open(path, File.WRITE)
    if err != OK:
        printerr("Could not write file, error code ", err)
        return
    f.store_string(text)
    f.close()

Load from game resources:

var text = load_text_file("res://path/to/file.txt")

Load from player savegame:

var text = load_text_file("user://path/to/file.txt")

Check this out for more info about reading and writing to files: https://godotengine.org/qa/6491/read-%26-write

by (27,952 points)
edited by

I would be useful to know if there's any technical or philosophical reason for not properly exposing TextFile in GDScript. I'm coming from a Unity background, where the TextAsset provides the functionality TextFile would, and I've found it an incredibly useful for creating textual resources (eg dialogue) and things like lookup tables (.csv for purposes other than translation). Obviously it's possible to just read the file in from a res:// path, but given that the resource type already exists, it would be nice not to have to do that.

I doubt it has any philosophical reason. What's more likely is that someone, some day, had a problem and wanted to be able to open and edit text files within the script editor. Then someone made a PR which does only that, was merged, and here we go (https://github.com/godotengine/godot/pull/19225)

If we want to expose its methods, I guess another PR should be made...

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.