Skip to reading
GDScript Programming & Godot

18. Native file reading, writing and appending

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page
Code example
func run() -> String:
    var path: String = "user://gdscript_tutorial_notes.txt"
    var output: FileAccess = FileAccess.open(path, FileAccess.WRITE)
    if output == null:
        return error_string(FileAccess.get_open_error())
    output.store_string("Visited the archive.\n")
    output.close()
    var input: FileAccess = FileAccess.open(path, FileAccess.READ)
    if input == null:
        return "Read failed"
    return input.get_as_text()

user:// is the writable data directory for the running application. res:// is its packaged Godot resource root. FileAccess.WRITE replaces the file. READ_WRITE opens an existing file for both directions; WRITE_READ creates/truncates one.

Code example
func append_line(path: String, line: String) -> Error:
    var mode: FileAccess.ModeFlags = FileAccess.WRITE_READ
    if FileAccess.file_exists(path):
        mode = FileAccess.READ_WRITE
    var file: FileAccess = FileAccess.open(path, mode)
    if file == null:
        return FileAccess.get_open_error()
    file.seek_end()
    file.store_line(line)
    file.close()
    return OK

To edit a specific line in a text file, read it, split it into lines, change the String array and rewrite the complete text. File cursor positions are bytes; do not assume an arbitrary byte offset is a safe character boundary in UTF-8 text.

PCA’s WriteTextFile/WriteJSONFile helpers accept user:// only. Native FileAccess is a Godot API with the platform’s filesystem permissions; it is not the same restricted helper. Use user:// for portable player data.

Page 27 of 378Permalink
Go to page