Is there a way how to export a value to a txt document?
I have a value I’m using in-game and I’d like to know if there is a way how to export it while in-game to a txt document.
Sure, here’s an example file:
ex_saveload.blend (93.3 KB)
from bge.logic import expandPath, getCurrentController
from ast import literal_eval
cont = getCurrentController()
own = cont.owner
# Sensors
save = cont.sensors["S"]
load = cont.sensors["L"]
# File path relative to current blend
filePath = expandPath("//my_file.txt")
# When S button is pressed
if save.positive:
try:
# Consolidate in a dict the data you want to save
dataYouWantToSave = {
"AProperty" : own["AProperty"],
"AnotherProperty" : own["AnotherProperty"]
}
# Write value to file
with open(filePath, "w") as openedFile:
# Convert consolidated data to str and write to file
openedFile.write(str(dataYouWantToSave))
print("Saved data to", openedFile.name)
except:
print("Could not save values to file")
# When L button is pressed
if load.positive:
try:
# Read value from file
with open(filePath, "r") as openedFile:
# Read str from file and convert it back to dict
loadedData = literal_eval(openedFile.read())
# Set object properties to loaded values
own["AProperty"] = loadedData["AProperty"]
own["AnotherProperty"] = loadedData["AnotherProperty"]
print("Loaded data from", openedFile.name)
except:
print("Could not read values from file")
2 Likes
Thank you, this is exactly what I’ve needed.
1 Like