Get_as_text() returning empty string for valid UTF-8 text file

Godot Version

4.2.2

Question

Hello! I’m debugging an issue where my game will periodically fail to read the settings file, so I created a validate_settings() function:

func validate_settings():
	var settings_file = FileAccess.open(settings_path, FileAccess.READ)
	var settings_text
	if settings_file.get_as_text() == "":
		settings_file.close()
		return 1
	else:
		settings_text = settings_file.get_as_text()
	var json = JSON.new()
	json.parse(settings_text)
	settings_file.close()
	if json.data == null:
		settings_file.close()
		return 2
	else:
		settings_file.close()
		return 0

It’s returning 1 every time I try to load the settings into the game when it first loads up. I know the settings_path variable is set correctly because I’ve referenced that elsewhere in my code and it’s working there. I also verified the text file is in the right encoding. I can’t think of anything else I could be doing wrong.

It should work fine.

If it does not then it has to be some logic error in your code. Maybe you are modifying it and not closing it before validating it or something like that.

Double check that you are getting a file object.

func validate_settings():
	var settings_file = FileAccess.open(settings_path, FileAccess.READ)
    print(settings_file)

If this prints null you have a file path issue.
Or I guess if it is only periodically showing an issue then try catching any open error.

func validate_settings():
	var settings_file = FileAccess.open(settings_path, FileAccess.READ)
    if settings_file.get_as_text() == "":
        print(settings_file.get_open_error() 
		settings_file.close()
		return 1
1 Like

This was exactly the problem, thanks!