0 votes

With the following code I'm having the file truncated, not appended.

    if ficheiro.open(nome_ficheiro, File.READ_WRITE) == OK:
        ficheiro.store_line(linha)
        ficheiro.close()

Is this supposed to erase the contents of the file?
I had the idea that, for truncating, there is WRITE_READ. Is this a bug?

Also, is there a way to create a file if it does not exist and ONLY append if it exists?
(I mean another way besides reading the file and writing it back all together)

in Engine by (104 points)

I think the string has to be in quotations

But this code writes the string successfully.
The point is that it does not append a new line to the file as it should but instead deletes the string it was saved there before and writes the new one. So, instead of getting a file with a content like this:
StringRun1
StringRun2
StringRun3

I get:
StringRun3

1 Answer

+2 votes
Best answer

You can use the method .seek_end() to move to the end of file. If you don't position inside the file it will (probably) overwrite the file from the beginning.

by (3,252 points)
selected by

You're right.
I've ended up with:

    if ficheiro.file_exists(nome_ficheiro):
        stat = ficheiro.open(nome_ficheiro, File.READ_WRITE)
    else:
        stat = ficheiro.open(nome_ficheiro, File.WRITE)

    if stat == OK:
        ficheiro.seek_end()
        ficheiro.store_line(linha)
        ficheiro.close()

This does it.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.