Open text file with a variable

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

Hi, I want to get the value from .txt file from a variable so I can use it further.
I have a code but it’s not working

var value= int(“user://value.txt”)

Anyone help?

:bust_in_silhouette: Reply From: USBashka

I think you need to use store_var() and get_var() in File class. Use this functions:

func save(content, path = "user://value.dat"):
    var file = File.new()
    file.open(path, File.WRITE)
    file.store_var(content)
    file.close()

func load(path = "user://value.dat"):
    var file = File.new()
    file.open(path, File.READ)
    var content = file.get_var()
    file.close()
    return content

With this code added you will be able to save any variable like save(42) and then load it like var value = load(). You can change the name of functions if you want or use them with another path: save(228, "user://another_value.txt"), load("user://another_value.txt")

Note that it is not text file, but data file, stores variable in binary.

Thank you, it was not quite what I needed but If I may have another question…I used this previously and it worked but it throws the error get_line: File must be opened before use

var file4 = File.new()
file4.open(“user://hellofile”, File.READ)
hello = int(file4.get_line())
file4.close()

What is wrong here? I am saving and opening numbers in that file.

Dream | 2022-07-14 14:38

Not sure. Maybe file hellofile is not exists yet? If you have created that file manually, note that Windows automatically adds extension to the files (and don’t show them by default), so name can be hellofile.txt. Also remember, where user:// directory is: Click on Project in the top menu and Open Project Data Folder.

USBashka | 2022-07-14 14:48

OMG Thank you so much, it was the file extension problem !

Dream | 2022-07-14 15:49