Append Text data to Json/Txt file

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

Python comes with a “a” (Append) flag to append text data to an existing txt/json file(refer).

However, in gdscript such an option is not provided (refer).

Any workarounds ?

:bust_in_silhouette: Reply From: Mindscore

I would make the following suggestion:

var file = File.new()
var path = "user://example.txt"

if file.file_exists(path):
	file.open(path, File.READ_WRITE)
	file.seek_end()
else:
	file.open(path, File.WRITE)

# append lines to file
file.store_line("example")

file.close()

You can obviously shorten the code when you are sure that the file already exists.
The key method here is seek_end()