How to append game data to a txt file?

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


I’m trying to write data from my game to a txt file. Here’s the example code:

func collect_data():
    var data = "my data"
    var file ="res://data.txt", File.WRITE)

This is essentially added to a button and activated when pressed, the button generates new data every time. Everything is working fine, I’m getting the data correct it’s writing to file as well. The problem is whenever the button is pressed the current data overwrites the previous one.

I would like to keep all the data the button presses, but I can’t figure out how to do that. I should mention that I’m using Godot to create a game for research purposes (PhD student) hence why I keep mentioning ‘data’ lol. The data is basically elements in the game state.

From what I’ve seen, you may have to first read the contents of the file (when it does have data), append the data to an object which contains the file’s data, and then write the object to the original file.

Then again, I have rarely used the file capabilities of the engine, so maybe there is a way to append the data to a current file without having a temporary variable.

Ertain | 2019-07-03 15:54

Hello! I’m also doing the same thing (creating godot game for research purposes). I’m curious how you ended up solving this. It looks like you were easily able to change your code based on the answer below, but how were you saving your data? Was it in a dictionary? currently my code is

func _save():
	var FILE_NAME = "res://Data/Becca" + str(month) + "_" + str(day) + "_" + str(year) + ".txt"
	var data = ""
	data += "Time: " + str(hour) + ":" + str(minute)
	data += "Level: " + str(level)
	data += "Target_Objects_Points: " + str(targetObjectsPoints)
	data += "\n"
	data += "Distractor_Objects_Points: " + str(distractorObjectsPoints)
	data += "\n"
	data += "Missed_Objects: " + str(missedObjectsPoints)
	data += "\n"
	var new_file =, File.WRITE)
	#Store the data and close the file
	print("file saved!")

but it is clunky and ultimately i’d like to save it in a dictionary. is your var data = "my data" stored as a dictionary?

Thanks in advance!

miss_bisque | 2021-02-25 03:57

miss_bisque: You should ask a new question for that :slight_smile:

Calinou | 2021-02-26 14:04

:bust_in_silhouette: Reply From: Dlean Jeans

Open with File.READ_WRITE:"res://data.txt", File.READ_WRITE)

Aaah that did the trick, thanks!

namathos | 2019-07-08 10:11