How can I read and write from / to a text file (res://, user://)

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

Hi,

I have an app with a data.txt file in the root folder (comes pre-loaded on a mobile with the app). I want to read and write to this file. I can read from the file using res:// but I cannot write to it since I have to use ‘user://’ prefix, which points to a different location I believe.

Here’s my code fragment:

func _on_btn_read_pressed():
	var file_read = File.new()
	if(file_read.open("res://data.txt", File.READ) != 0):
		$lbl_file_data.text = "error opening file"
	else:
		$lbl_file_data.text = file_read.get_as_text()
		file_read.close()
	pass 


func _on_btn_write_pressed():
    var text = $TextEdit.text
	var file_write = File.new()
	if(!file_write.file_exists("user://data.txt")):
		$lbl_file_data.text = "no file to write to"
   elif(file_write.open("user://data.txt", File.WRITE) != 0):
		$lbl_file_data.text = "error writing to file"
	else:
		file_write.seek_end()
		file_write.store_line(text)
		file_write.close()

How can I write to the same file that I read data from? Do I have to create a file programatically on app startup?

Thanks

ps…the automatic ‘code sample’ button in writing this question may create erroneous code formatting

:bust_in_silhouette: Reply From: volzhs

you need to specify *.txt at the export setting to include non-godot resource.

Export > Select target platform > Resources tab on right side > Filters to export non-resource files

It doesn’t work:
I have “res://level1.txt” file and I specify *.txt at the export setting to include non-godot resource.
at runtime, still file not found error.

burstina | 2019-10-11 21:15

I am running into this same problem with a .json file I have in my project at res://strings/en_US.json – When I extract the exported .apk file, it doesn’t contain the strings/ folder or anything inside of it. I’ve specified *.json in my export settings.

LudditeGames | 2019-11-04 01:12