Why FileAccess.open returns null?

Godot Version

4.3 stable

Question

Code:

func _write_log():
	var path = "user://conosolelogs"
	var time : String = Time.get_time_string_from_system()
	var filename : String = "consolelog_"+time+".txt"
	var dirAccess = DirAccess.open("user://")
	
	if dirAccess == null:
		print("DirAccess is null")
	else:
		dirAccess.make_dir(path)
	
	var file = FileAccess.open(path+filename, FileAccess.WRITE)
	
	file.store_line("test") # error here
	file.close()

Error message: Attempt to call function ‘store_line’ in base ‘null instance’ on a null instance.

The directory “conosolelogs” was created successfully, but it seems to not be able to open the file. Does anyone know how to fix this?

Thanks in advance!

Try to use path + "/" + filename

I definitely had to write "/consolelog_"+time+".txt" or path+"/"+filename but still the same error occurs.

you can detect open errors with FileAcess.get_open_error()

var file := FileAccess.open(path.path_join(filename), FileAccess.WRITE)
if file == null:
	var error_str: String = error_string(FileAccess.get_open_error())
	push_warning("Couldn't open file because: %s" % error_str)

It looks like your time variable contains colons :, which are illegal filename characters in Windows.

3 Likes

Changing Time.get_time_string_from_system() to Time.get_date_string_from_system() solved this problem and now it works without any errors or warnings. Thanks!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.