File type. This is used to permanently store data into the user device's file system and to read from it. This can be used to store game save data or player configuration files, for example.

Here's a sample on how to write and read from a file:


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

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

In the example above, the file will be saved in the user data folder as specified in the [https://docs.godotengine.org/en/3.4/tutorials/io/data_paths.html](Data paths) documentation.

Note: To access project resources once exported, it is recommended to use godot.ResourceLoader instead of the godot.File API, as some files are converted to engine-specific formats and their original source files might not be present in the exported PCK package.

Note: Files are automatically closed only if the process exits "normally" (such as by clicking the window manager's close button or pressing Alt + F4). If you stop the project execution by pressing F8 while the project is running, the file won't be closed as the game process will be killed. You can work around this by calling godot.File.flush at regular intervals.

Constructor

@:native("new")new()

Variables

@:native("EndianSwap")endianSwap:Bool

If true, the file is read with big-endian [https://en.wikipedia.org/wiki/Endianness](endianness). If false, the file is read with little-endian endianness. If in doubt, leave this to false as most files are written with little-endian endianness.

Note: godot.File.endianSwap is only about the file format, not the CPU type. The CPU endianness doesn't affect the default endianness for files written.

Note: This is always reset to false whenever you open the file. Therefore, you must set godot.File.endianSwap after opening the file, not before.

Methods

@:native("Close")close():Void

Closes the currently opened file and prevents subsequent read/write operations. Use godot.File.flush to persist the data to disk without closing the file.

@:native("EofReached")eofReached():Bool

Returns true if the file cursor has already read past the end of the file.

Note: eof_reached() == false cannot be used to check whether there is more data available. To loop while there is more data available, use:


while file.get_position() < file.get_len():
# Read data

@:native("FileExists")fileExists(path:String):Bool

Returns true if the file exists in the given path.

Note: Many resources types are imported (e.g. textures or sound files), and their source asset will not be included in the exported game, as only the imported version is used. See godot.ResourceLoader.exists for an alternative approach that takes resource remapping into account.

@:native("Flush")flush():Void

Writes the file's buffer to disk. Flushing is automatically performed when the file is closed. This means you don't need to call godot.File.flush manually before closing a file using godot.File.close. Still, calling godot.File.flush can be used to ensure the data is safe even if the project crashes instead of being closed gracefully.

Note: Only call godot.File.flush when you actually need it. Otherwise, it will decrease performance due to constant disk writes.

@:native("Get16")get16():UInt16

Returns the next 16 bits from the file as an integer. See godot.File.store16 for details on what values can be stored and retrieved this way.

@:native("Get32")get32():UInt

Returns the next 32 bits from the file as an integer. See godot.File.store32 for details on what values can be stored and retrieved this way.

@:native("Get64")get64():UInt64

Returns the next 64 bits from the file as an integer. See godot.File.store64 for details on what values can be stored and retrieved this way.

@:native("Get8")get8():UInt8

Returns the next 8 bits from the file as an integer. See godot.File.store8 for details on what values can be stored and retrieved this way.

@:native("GetAsText")getAsText():String

Returns the whole file as a String.

Text is interpreted as being UTF-8 encoded.

inlinegetBuffer(len:Int64):Array<UInt8>

Returns next len bytes of the file as a cs.UInt8.

inlinegetCsvLine(?delim:String):Array<String>

Returns the next value of the file in CSV (Comma-Separated Values) format. You can pass a different delimiter delim to use other than the default "," (comma). This delimiter must be one-character long, and cannot be a double quotation mark.

Text is interpreted as being UTF-8 encoded. Text values must be enclosed in double quotes if they include the delimiter character. Double quotes within a text value can be escaped by doubling their occurrence.

For example, the following CSV lines are valid and will be properly parsed as two strings each:


Alice,"Hello, Bob!"
Bob,Alice! What a surprise!
Alice,"I thought you'd reply with ""Hello, world""."

Note how the second line can omit the enclosing quotes as it does not include the delimiter. However it could very well use quotes, it was only written without for demonstration purposes. The third line must use "" for each quotation mark that needs to be interpreted as such instead of the end of a text value.

@:native("GetDouble")getDouble():Float

Returns the next 64 bits from the file as a floating-point number.

@:native("GetEndianSwap")getEndianSwap():Bool

@:native("GetError")getError():Error

Returns the last error that happened when trying to perform operations. Compare with the ERR_FILE_* constants from godot.Error.

@:native("GetFloat")getFloat():Single

Returns the next 32 bits from the file as a floating-point number.

@:native("GetLen")getLen():UInt64

Returns the size of the file in bytes.

@:native("GetLine")getLine():String

Returns the next line of the file as a String.

Text is interpreted as being UTF-8 encoded.

@:native("GetMd5")getMd5(path:String):String

Returns an MD5 String representing the file at the given path or an empty String on failure.

@:native("GetModifiedTime")getModifiedTime(file:String):UInt64

Returns the last time the file was modified in unix timestamp format or returns a String "ERROR IN file". This unix timestamp can be converted to datetime by using godot.OS.getDatetimeFromUnixTime.

@:native("GetPascalString")getPascalString():String

Returns a String saved in Pascal format from the file.

Text is interpreted as being UTF-8 encoded.

@:native("GetPath")getPath():String

Returns the path as a String for the current open file.

@:native("GetPathAbsolute")getPathAbsolute():String

Returns the absolute path as a String for the current open file.

@:native("GetPosition")getPosition():UInt64

Returns the file cursor's position.

@:native("GetReal")getReal():Single

Returns the next bits from the file as a floating-point number.

@:native("GetSha256")getSha256(path:String):String

Returns a SHA-256 String representing the file at the given path or an empty String on failure.

@:native("GetVar")getVar(?allowObjects:Bool):Dynamic

Returns the next Variant value from the file. If allow_objects is true, decoding objects is allowed.

Warning: Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.

@:native("IsOpen")isOpen():Bool

Returns true if the file is currently opened.

@:native("Open")open(path:String, flags:File_ModeFlags):Error

Opens the file for writing or reading, depending on the flags.

@:native("OpenCompressed")openCompressed(path:String, modeFlags:File_ModeFlags, ?compressionMode:File_CompressionMode):Error

Opens a compressed file for reading or writing.

Note: godot.File.openCompressed can only read files that were saved by Godot, not third-party compression formats. See [https://github.com/godotengine/godot/issues/28999](GitHub issue #28999) for a workaround.

@:native("OpenEncrypted")openEncrypted(path:String, modeFlags:File_ModeFlags, key:HaxeArray<UInt8>):Error

Opens an encrypted file in write or read mode. You need to pass a binary key to encrypt/decrypt it.

Note: The provided key must be 32 bytes long.

@:native("OpenEncryptedWithPass")openEncryptedWithPass(path:String, modeFlags:File_ModeFlags, pass:String):Error

Opens an encrypted file in write or read mode. You need to pass a password to encrypt/decrypt it.

@:native("Seek")seek(position:Int64):Void

Changes the file reading/writing cursor to the specified position (in bytes from the beginning of the file).

@:native("SeekEnd")seekEnd(?position:Int64):Void

Changes the file reading/writing cursor to the specified position (in bytes from the end of the file).

Note: This is an offset, so you should use negative numbers or the cursor will be at the end of the file.

@:native("SetEndianSwap")setEndianSwap(enable:Bool):Void

@:native("Store16")store16(value:UInt16):Void

Stores an integer as 16 bits in the file.

Note: The value should lie in the interval [0, 2^16 - 1]. Any other value will overflow and wrap around.

To store a signed integer, use godot.File.store64 or store a signed integer from the interval [-2^15, 2^15 - 1] (i.e. keeping one bit for the signedness) and compute its sign manually when reading. For example:


const MAX_15B = 1 &lt;&lt; 15
const MAX_16B = 1 &lt;&lt; 16

func unsigned16_to_signed(unsigned):
return (unsigned + MAX_15B) % MAX_16B - MAX_15B

func _ready():
var f = File.new()
f.open("user://file.dat", File.WRITE_READ)
f.store_16(-42) # This wraps around and stores 65494 (2^16 - 42).
f.store_16(121) # In bounds, will store 121.
f.seek(0) # Go back to start to read the stored value.
var read1 = f.get_16() # 65494
var read2 = f.get_16() # 121
var converted1 = unsigned16_to_signed(read1) # -42
var converted2 = unsigned16_to_signed(read2) # 121

@:native("Store32")store32(value:UInt):Void

Stores an integer as 32 bits in the file.

Note: The value should lie in the interval [0, 2^32 - 1]. Any other value will overflow and wrap around.

To store a signed integer, use godot.File.store64, or convert it manually (see godot.File.store16 for an example).

@:native("Store64")store64(value:UInt64):Void

Stores an integer as 64 bits in the file.

Note: The value must lie in the interval [-2^63, 2^63 - 1] (i.e. be a valid Int value).

@:native("Store8")store8(value:UInt8):Void

Stores an integer as 8 bits in the file.

Note: The value should lie in the interval [0, 255]. Any other value will overflow and wrap around.

To store a signed integer, use godot.File.store64, or convert it manually (see godot.File.store16 for an example).

@:native("StoreBuffer")storeBuffer(buffer:HaxeArray<UInt8>):Void

Stores the given array of bytes in the file.

@:native("StoreCsvLine")storeCsvLine(values:Array<String>, ?delim:String):Void

Store the given String in the file as a line formatted in the CSV (Comma-Separated Values) format. You can pass a different delimiter delim to use other than the default "," (comma). This delimiter must be one-character long.

Text will be encoded as UTF-8.

@:native("StoreDouble")storeDouble(value:Float):Void

Stores a floating-point number as 64 bits in the file.

@:native("StoreFloat")storeFloat(value:Single):Void

Stores a floating-point number as 32 bits in the file.

@:native("StoreLine")storeLine(line:String):Void

Appends line to the file followed by a line return character (\n), encoding the text as UTF-8.

@:native("StorePascalString")storePascalString(string:String):Void

Stores the given String as a line in the file in Pascal format (i.e. also store the length of the string).

Text will be encoded as UTF-8.

@:native("StoreReal")storeReal(value:Single):Void

Stores a floating-point number in the file.

@:native("StoreString")storeString(string:String):Void

Appends string to the file without a line return, encoding the text as UTF-8.

Note: This method is intended to be used to write text files. The string is stored as a UTF-8 encoded buffer without string length or terminating zero, which means that it can't be loaded back easily. If you want to store a retrievable string in a binary file, consider using godot.File.storePascalString instead. For retrieving strings from a text file, you can use get_buffer(length).get_string_from_utf8() (if you know the length) or godot.File.getAsText.

@:native("StoreVar")storeVar(value:Dynamic, ?fullObjects:Bool):Void

Stores any Variant value in the file. If full_objects is true, encoding objects is allowed (and can potentially include code).

Note: Not all properties are included. Only properties that are configured with the PROPERTY_USAGE_STORAGE flag set will be serialized. You can add a new usage flag to a property by overriding the godot.Object._GetPropertyList method in your class. You can also check how property usage is configured by calling godot.Object._GetPropertyList. See godot.PropertyUsageFlags for the possible usage flags.

Inherited Variables

Defined by Object

@:native("DynamicObject")read onlydynamicObject:Dynamic

Gets a new godot.DynamicGodotObject associated with this instance.

@:native("NativeInstance")read onlynativeInstance:IntPtr

The pointer to the native instance of this godot.Object.

read onlyonScriptChanged:Signal<() ‑> Void>

script_changed signal.

Inherited Methods

Defined by Reference

@:native("InitRef")initRef():Bool

Initializes the internal reference counter. Use this only if you really know what you are doing.

Returns whether the initialization was successful.

@:native("Reference_")reference_():Bool

Increments the internal reference counter. Use this only if you really know what you are doing.

Returns true if the increment was successful, false otherwise.

@:native("Unreference")unreference():Bool

Decrements the internal reference counter. Use this only if you really know what you are doing.

Returns true if the decrement was successful, false otherwise.

Defined by Object

@:native("_Get")_Get(property:String):Dynamic

Virtual method which can be overridden to customize the return value of godot.Object.get.

Returns the given property. Returns null if the property does not exist.

@:native("_GetPropertyList")_GetPropertyList():Array

Virtual method which can be overridden to customize the return value of godot.Object.getPropertyList.

Returns the object's property list as an godot.Collections_Array of dictionaries.

Each property's godot.Collections_Dictionary must contain at least name: String and type: int (see godot.Variant_Type) entries. Optionally, it can also include hint: int (see godot.PropertyHint), hint_string: String, and usage: int (see godot.PropertyUsageFlags).

@:native("_Notification")_Notification(what:Int):Void

Called whenever the object receives a notification, which is identified in what by a constant. The base godot.Object has two constants godot.Object.notificationPostinitialize and godot.Object.notificationPredelete, but subclasses such as godot.Node define a lot more notifications which are also received by this method.

@:native("_Set")_Set(property:String, value:Dynamic):Bool

Virtual method which can be overridden to customize the return value of godot.Object.set.

Sets a property. Returns true if the property exists.

@:native("AddUserSignal")addUserSignal(signal:String, ?arguments:Array):Void

Adds a user-defined signal. Arguments are optional, but can be added as an godot.Collections_Array of dictionaries, each containing name: String and type: int (see godot.Variant_Type) entries.

Parameters:

arguments

If the parameter is null, then the default value is new Godot.Collections.Array { }

@:native("Call")call(method:String, args:HaxeArray<Dynamic>):Dynamic

Calls the method on the object and returns the result. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:


call("set", "position", Vector2(42.0, 0.0))

Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).

@:native("CallDeferred")callDeferred(method:String, args:HaxeArray<Dynamic>):Void

Calls the method on the object during idle time. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:


call_deferred("set", "position", Vector2(42.0, 0.0))

Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).

@:native("Callv")callv(method:String, argArray:Array):Dynamic

Calls the method on the object and returns the result. Contrarily to godot.Object.call, this method does not support a variable number of arguments but expects all parameters to be via a single godot.Collections_Array.


callv("set", [ "position", Vector2(42.0, 0.0) ])

@:native("CanTranslateMessages")canTranslateMessages():Bool

Returns true if the object can translate strings. See godot.Object.setMessageTranslation and godot.Object.tr.

@:native("Connect")connect(signal:String, target:Object, method:String, ?binds:Array, ?flags:UInt):Error

Connects a signal to a method on a target object. Pass optional binds to the call as an godot.Collections_Array of parameters. These parameters will be passed to the method after any parameter used in the call to godot.Object.emitSignal. Use flags to set deferred or one-shot connections. See godot.Object_ConnectFlags constants.

A signal can only be connected once to a method. It will print an error if already connected, unless the signal was connected with godot.Object_ConnectFlags.referenceCounted. To avoid this, first, use godot.Object.isConnected to check for existing connections.

If the target is destroyed in the game's lifecycle, the connection will be lost.

Examples:


connect("pressed", self, "_on_Button_pressed") # BaseButton signal
connect("text_entered", self, "_on_LineEdit_text_entered") # LineEdit signal
connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # User-defined signal

An example of the relationship between binds passed to godot.Object.connect and parameters used when calling godot.Object.emitSignal:


connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # weapon_type and damage are passed last
emit_signal("hit", "Dark lord", 5) # "Dark lord" and 5 are passed first
func _on_Player_hit(hit_by, level, weapon_type, damage):
print("Hit by %s (lvl %d) with weapon %s for %d damage" % [hit_by, level, weapon_type, damage])

Parameters:

binds

If the parameter is null, then the default value is new Godot.Collections.Array { }

@:native("Disconnect")disconnect(signal:String, target:Object, method:String):Void

Disconnects a signal from a method on the given target.

If you try to disconnect a connection that does not exist, the method will print an error. Use godot.Object.isConnected to ensure that the connection exists.

@:native("Dispose")dispose():Void

@:native("Dispose")@:protectedDispose(disposing:Bool):Void

Disposes of this godot.Object.

@:native("EmitSignal")emitSignal(signal:String, args:HaxeArray<Dynamic>):Void

Emits the given signal. The signal must exist, so it should be a built-in signal of this class or one of its parent classes, or a user-defined signal. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:


emit_signal("hit", weapon_type, damage)
emit_signal("game_over")

@:native("Free")free():Void

Deletes the object from memory immediately. For godot.Nodes, you may want to use godot.Node.queueFree to queue the node for safe deletion at the end of the current frame.

Important: If you have a variable pointing to an object, it will not be assigned to null once the object is freed. Instead, it will point to a previously freed instance and you should validate it with @GDScript.is_instance_valid before attempting to call its methods or access its properties.

@:native("Get")get(property:String):Dynamic

Returns the Variant value of the given property. If the property doesn't exist, this will return null.

Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase).

@:native("GetClass")getClass():String

Returns the object's class as a String. See also godot.Object.isClass.

Note: godot.Object.getClass does not take class_name declarations into account. If the object has a class_name defined, the base class name will be returned instead.

@:native("GetIncomingConnections")getIncomingConnections():Array

Returns an godot.Collections_Array of dictionaries with information about signals that are connected to the object.

Each godot.Collections_Dictionary contains three String entries:

  • source is a reference to the signal emitter.

  • signal_name is the name of the connected signal.

  • method_name is the name of the method to which the signal is connected.

@:native("GetIndexed")getIndexed(property:NodePath):Dynamic

Gets the object's property indexed by the given godot.NodePath. The node path should be relative to the current object and can use the colon character (:) to access nested properties. Examples: "position:x" or "material:next_pass:blend_mode".

Note: Even though the method takes godot.NodePath argument, it doesn't support actual paths to godot.Nodes in the scene tree, only colon-separated sub-property paths. For the purpose of nodes, use godot.Node.getNodeAndResource instead.

@:native("GetInstanceId")getInstanceId():UInt64

Returns the object's unique instance ID.

This ID can be saved in godot.EncodedObjectAsID, and can be used to retrieve the object instance with @GDScript.instance_from_id.

@:native("GetMeta")getMeta(name:String):Dynamic

Returns the object's metadata entry for the given name.

inlinegetMetaList():Array<String>

Returns the object's metadata as a String.

@:native("GetMethodList")getMethodList():Array

Returns the object's methods and their signatures as an godot.Collections_Array.

@:native("GetPropertyList")getPropertyList():Array

Returns the object's property list as an godot.Collections_Array of dictionaries.

Each property's godot.Collections_Dictionary contain at least name: String and type: int (see godot.Variant_Type) entries. Optionally, it can also include hint: int (see godot.PropertyHint), hint_string: String, and usage: int (see godot.PropertyUsageFlags).

@:native("GetScript")getScript():Reference

Returns the object's godot.Script instance, or null if none is assigned.

@:native("GetSignalConnectionList")getSignalConnectionList(signal:String):Array

Returns an godot.Collections_Array of connections for the given signal.

@:native("GetSignalList")getSignalList():Array

Returns the list of signals as an godot.Collections_Array of dictionaries.

@:native("HasMeta")hasMeta(name:String):Bool

Returns true if a metadata entry is found with the given name.

@:native("HasMethod")hasMethod(method:String):Bool

Returns true if the object contains the given method.

@:native("HasSignal")hasSignal(signal:String):Bool

Returns true if the given signal exists.

@:native("HasUserSignal")hasUserSignal(signal:String):Bool

Returns true if the given user-defined signal exists. Only signals added using godot.Object.addUserSignal are taken into account.

@:native("IsBlockingSignals")isBlockingSignals():Bool

Returns true if signal emission blocking is enabled.

@:native("IsClass")isClass(class_:String):Bool

Returns true if the object inherits from the given class. See also godot.Object.getClass.

Note: godot.Object.isClass does not take class_name declarations into account. If the object has a class_name defined, godot.Object.isClass will return false for that name.

@:native("IsConnected")isConnected(signal:String, target:Object, method:String):Bool

Returns true if a connection exists for a given signal, target, and method.

@:native("IsQueuedForDeletion")isQueuedForDeletion():Bool

Returns true if the godot.Node.queueFree method was called for the object.

@:native("Notification")notification(what:Int, ?reversed:Bool):Void

Send a given notification to the object, which will also trigger a call to the godot.Object._Notification method of all classes that the object inherits from.

If reversed is true, godot.Object._Notification is called first on the object's own class, and then up to its successive parent classes. If reversed is false, godot.Object._Notification is called first on the highest ancestor (godot.Object itself), and then down to its successive inheriting classes.

@:native("PropertyListChangedNotify")propertyListChangedNotify():Void

Notify the editor that the property list has changed, so that editor plugins can take the new values into account. Does nothing on export builds.

@:native("RemoveMeta")removeMeta(name:String):Void

Removes a given entry from the object's metadata. See also godot.Object.setMeta.

@:native("Set")set(property:String, value:Dynamic):Void

Assigns a new value to the given property. If the property does not exist or the given value's type doesn't match, nothing will happen.

Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase).

@:native("SetBlockSignals")setBlockSignals(enable:Bool):Void

If set to true, signal emission is blocked.

@:native("SetDeferred")setDeferred(property:String, value:Dynamic):Void

Assigns a new value to the given property, after the current frame's physics step. This is equivalent to calling godot.Object.set via godot.Object.callDeferred, i.e. call_deferred("set", property, value).

Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase).

@:native("SetIndexed")setIndexed(property:NodePath, value:Dynamic):Void

Assigns a new value to the property identified by the godot.NodePath. The node path should be relative to the current object and can use the colon character (:) to access nested properties. Example:


set_indexed("position", Vector2(42, 0))
set_indexed("position:y", -10)
print(position) # (42, -10)

@:native("SetMessageTranslation")setMessageTranslation(enable:Bool):Void

Defines whether the object can translate strings (with calls to godot.Object.tr). Enabled by default.

@:native("SetMeta")setMeta(name:String, value:Dynamic):Void

Adds, changes or removes a given entry in the object's metadata. Metadata are serialized and can take any Variant value.

To remove a given entry from the object's metadata, use godot.Object.removeMeta. Metadata is also removed if its value is set to null. This means you can also use set_meta("name", null) to remove metadata for "name".

@:native("SetScript")setScript(script:Reference):Void

Assigns a script to the object. Each object can have a single script assigned to it, which are used to extend its functionality.

If the object already had a script, the previous script instance will be freed and its variables and state will be lost. The new script's method will be called.

@:native("ToSignal")toSignal(source:Object, signal:String):SignalAwaiter

Returns a new godot.SignalAwaiter awaiter configured to complete when the instance source emits the signal specified by the signal parameter.

Parameters:

source

The instance the awaiter will be listening to.

signal

The signal the awaiter will be waiting for. This sample prints a message once every frame up to 100 times.

public override void _Ready()
{
for (int i = 0; i &lt; 100; i++)
{
await ToSignal(GetTree(), "idle_frame");
GD.Print($"Frame {i}");
}
}

Returns:

A godot.SignalAwaiter that completes when source emits the signal.

@:native("ToString")toString():String

Converts this godot.Object to a string.

Returns:

A string representation of this object.

@:native("Tr")tr(message:String):String

Translates a message using translation catalogs configured in the Project Settings.

Only works if message translation is enabled (which it is by default), otherwise it returns the message unchanged. See godot.Object.setMessageTranslation.