Can you read a TextFile resource with GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By INeeedHealing

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?

:bust_in_silhouette: Reply From: Zylann

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: Ability to create TextFiles. by Paulb23 · Pull Request #21022 · godotengine/godot · GitHub

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://forum.godotengine.org/6491/read-%26-write

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.

S Arrowsmith | 2020-08-29 21:30

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…

Zylann | 2020-08-29 23:41