File Class |
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 Data paths documentation.
Note: To access project resources once exported, it is recommended to use ResourceLoader instead of the 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 Flush at regular intervals.
Namespace: Godot
public class File : Reference
The File type exposes the following members.
Name | Description | |
---|---|---|
DynamicObject |
Gets a new DynamicGodotObject associated with this instance.
(Inherited from Object.) | |
EndianSwap | If true, the file is read with big-endian 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: 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 EndianSwap after opening the file, not before. | |
NativeInstance | (Inherited from Object.) |
Name | Description | |
---|---|---|
_Get | Virtual method which can be overridden to customize the return value of Get(String). Returns the given property. Returns null if the property does not exist. | |
_GetPropertyList | Virtual method which can be overridden to customize the return value of GetPropertyList. Returns the object's property list as an Array of dictionaries. Each property's Dictionary must contain at least name: String and type: int (see VariantType) entries. Optionally, it can also include hint: int (see PropertyHint), hint_string: String, and usage: int (see PropertyUsageFlags). | |
_Notification | Called whenever the object receives a notification, which is identified in what by a constant. The base Object has two constants and , but subclasses such as Node define a lot more notifications which are also received by this method. | |
_Set | Virtual method which can be overridden to customize the return value of Set(String, Object). Sets a property. Returns true if the property exists. | |
AddUserSignal | Adds a user-defined signal. Arguments are optional, but can be added as an Array of dictionaries, each containing name: String and type: int (see VariantType) entries. | |
Call | 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). | |
CallDeferred | 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). | |
Callv | Calls the method on the object and returns the result. Contrarily to Call(String, Object), this method does not support a variable number of arguments but expects all parameters to be via a single Array. callv("set", [ "position", Vector2(42.0, 0.0) ]) | |
CanTranslateMessages | Returns true if the object can translate strings. See SetMessageTranslation(Boolean) and Tr(String). | |
Close | Closes the currently opened file and prevents subsequent read/write operations. Use Flush to persist the data to disk without closing the file. | |
Connect | Connects a signal to a method on a target object. Pass optional binds to the call as an Array of parameters. These parameters will be passed to the method after any parameter used in the call to EmitSignal(String, Object). Use flags to set deferred or one-shot connections. See ObjectConnectFlags constants. A signal can only be connected once to a method. It will throw an error if already connected, unless the signal was connected with . To avoid this, first, use IsConnected(String, Object, String) 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 Connect(String, Object, String, Array, UInt32) and parameters used when calling EmitSignal(String, Object): 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]) | |
Disconnect | Disconnects a signal from a method on the given target. If you try to disconnect a connection that does not exist, the method will throw an error. Use IsConnected(String, Object, String) to ensure that the connection exists. | |
Dispose | (Inherited from Object.) | |
Dispose(Boolean) | (Inherited from Object.) | |
EmitSignal | 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") | |
EofReached | Returns true if the file cursor has read past the end of the file. Note: This function will still return false while at the end of the file and only activates when reading past it. This can be confusing but it conforms to how low-level file access works in all operating systems. There is always GetLen and GetPosition to implement a custom logic. | |
Equals | (Inherited from Object.) | |
FileExists | 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 Exists(String, String) for an alternative approach that takes resource remapping into account. | |
Finalize | (Inherited from Object.) | |
Flush | Writes the file's buffer to disk. Flushing is automatically performed when the file is closed. This means you don't need to call Flush manually before closing a file using Close. Still, calling Flush can be used to ensure the data is safe even if the project crashes instead of being closed gracefully. Note: Only call Flush when you actually need it. Otherwise, it will decrease performance due to constant disk writes. | |
Free | Deletes the object from memory immediately. For Nodes, you may want to use 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. | |
Get | 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). | |
Get16 | Returns the next 16 bits from the file as an integer. See Store16(UInt16) for details on what values can be stored and retrieved this way. | |
Get32 | Returns the next 32 bits from the file as an integer. See Store32(UInt32) for details on what values can be stored and retrieved this way. | |
Get64 | Returns the next 64 bits from the file as an integer. See Store64(UInt64) for details on what values can be stored and retrieved this way. | |
Get8 | Returns the next 8 bits from the file as an integer. See Store8(Byte) for details on what values can be stored and retrieved this way. | |
GetAsText | Returns the whole file as a String. Text is interpreted as being UTF-8 encoded. | |
GetBuffer | Returns next len bytes of the file as a Byte. | |
GetClass | Returns the object's class as a String. | |
GetCsvLine | 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. Text is interpreted as being UTF-8 encoded. | |
GetDouble | Returns the next 64 bits from the file as a floating-point number. | |
GetEndianSwap | Obsolete. | |
GetError | Returns the last error that happened when trying to perform operations. Compare with the ERR_FILE_* constants from Error. | |
GetFloat | Returns the next 32 bits from the file as a floating-point number. | |
GetHashCode | (Inherited from Object.) | |
GetIncomingConnections | Returns an Array of dictionaries with information about signals that are connected to the object. Each 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. | |
GetIndexed | Gets the object's property indexed by the given 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". | |
GetInstanceId | Returns the object's unique instance ID. This ID can be saved in EncodedObjectAsID, and can be used to retrieve the object instance with @GDScript.instance_from_id. | |
GetLen | Returns the size of the file in bytes. | |
GetLine | Returns the next line of the file as a String. Text is interpreted as being UTF-8 encoded. | |
GetMd5 | Returns an MD5 String representing the file at the given path or an empty String on failure. | |
GetMeta | Returns the object's metadata entry for the given name. | |
GetMetaList | Returns the object's metadata as a String. | |
GetMethodList | Returns the object's methods and their signatures as an Array. | |
GetModifiedTime | 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 GetDatetimeFromUnixTime(Int64). | |
GetPascalString | Returns a String saved in Pascal format from the file. Text is interpreted as being UTF-8 encoded. | |
GetPath | Returns the path as a String for the current open file. | |
GetPathAbsolute | Returns the absolute path as a String for the current open file. | |
GetPosition | Returns the file cursor's position. | |
GetPropertyList | Returns the object's property list as an Array of dictionaries. Each property's Dictionary contain at least name: String and type: int (see VariantType) entries. Optionally, it can also include hint: int (see PropertyHint), hint_string: String, and usage: int (see PropertyUsageFlags). | |
GetReal | Returns the next bits from the file as a floating-point number. | |
GetScript | Returns the object's Script instance, or null if none is assigned. | |
GetSha256 | ||
GetSignalConnectionList | Returns an Array of connections for the given signal. | |
GetSignalList | Returns the list of signals as an Array of dictionaries. | |
GetType | (Inherited from Object.) | |
GetVar | 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. | |
HasMeta | Returns true if a metadata entry is found with the given name. | |
HasMethod | Returns true if the object contains the given method. | |
HasSignal | Returns true if the given signal exists. | |
HasUserSignal | Returns true if the given user-defined signal exists. Only signals added using AddUserSignal(String, Array) are taken into account. | |
InitRef | Initializes the internal reference counter. Use this only if you really know what you are doing. Returns whether the initialization was successful. | |
IsBlockingSignals | Returns true if signal emission blocking is enabled. | |
IsClass | Returns true if the object inherits from the given class. | |
IsConnected | Returns true if a connection exists for a given signal, target, and method. | |
IsOpen | Returns true if the file is currently opened. | |
IsQueuedForDeletion | Returns true if the QueueFree method was called for the object. | |
MemberwiseClone | (Inherited from Object.) | |
Notification | Send a given notification to the object, which will also trigger a call to the _Notification(Int32) method of all classes that the object inherits from. If reversed is true, _Notification(Int32) is called first on the object's own class, and then up to its successive parent classes. If reversed is false, _Notification(Int32) is called first on the highest ancestor (Object itself), and then down to its successive inheriting classes. | |
Open | Opens the file for writing or reading, depending on the flags. | |
OpenCompressed | Opens a compressed file for reading or writing. | |
OpenEncrypted | 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. | |
OpenEncryptedWithPass | Opens an encrypted file in write or read mode. You need to pass a password to encrypt/decrypt it. | |
PropertyListChangedNotify | 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. | |
Reference_ | 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. | |
RemoveMeta | Removes a given entry from the object's metadata. See also SetMeta(String, Object). | |
Seek | Changes the file reading/writing cursor to the specified position (in bytes from the beginning of the file). | |
SeekEnd | 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. | |
Set | Assigns a new value to the given property. If the property does not exist, 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). | |
SetBlockSignals | If set to true, signal emission is blocked. | |
SetDeferred | Assigns a new value to the given property, after the current frame's physics step. This is equivalent to calling Set(String, Object) via CallDeferred(String, Object), 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). | |
SetEndianSwap | Obsolete. | |
SetIndexed | Assigns a new value to the property identified by the 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) | |
SetMessageTranslation | Defines whether the object can translate strings (with calls to Tr(String)). Enabled by default. | |
SetMeta | 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 RemoveMeta(String). 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". | |
SetScript | 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. | |
Store16 | 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 Store64(UInt64) 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 << 15 const MAX_16B = 1 << 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 | |
Store32 | 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 Store64(UInt64), or convert it manually (see Store16(UInt16) for an example). | |
Store64 | 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 Int32 value). | |
Store8 | 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 Store64(UInt64), or convert it manually (see Store16(UInt16) for an example). | |
StoreBuffer | Stores the given array of bytes in the file. | |
StoreCsvLine | 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. | |
StoreDouble | Stores a floating-point number as 64 bits in the file. | |
StoreFloat | Stores a floating-point number as 32 bits in the file. | |
StoreLine | Appends line to the file followed by a line return character (\n), encoding the text as UTF-8. | |
StorePascalString | 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. | |
StoreReal | Stores a floating-point number in the file. | |
StoreString | Appends string to the file without a line return, encoding the text as UTF-8. | |
StoreVar | Stores any Variant value in the file. If full_objects is true, encoding objects is allowed (and can potentially include code). | |
ToSignal |
Returns a new SignalAwaiter awaiter configured to complete when the instance
source emits the signal specified by the signal parameter.
(Inherited from Object.) | |
ToString | (Inherited from Object.) | |
Tr | 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 SetMessageTranslation(Boolean). | |
Unreference | 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. |