File¶
Type to handle file reading and writing operations.
Description¶
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:
funcsave(content):varfile=File.new()file.open("user://save_game.dat",File.WRITE)file.store_string(content)file.close()funcload():varfile=File.new()file.open("user://save_game.dat",File.READ)varcontent=file.get_as_text()file.close()returncontent
In the example above, the file will be saved in the user data folder as specified in theData paths documentation.
Note: To access project resources once exported, it is recommended to useResourceLoader instead of theFile 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 pressingAlt + F4). If you stop the project execution by pressingF8 while the project is running, the file won't be closed as the game process will be killed. You can work around this by callingflush at regular intervals.
Tutorials¶
Properties¶
|
Methods¶
void | close() |
file_exists(String path)const | |
void | flush() |
get_buffer(int len)const | |
get_csv_line(String delim=",")const | |
get_modified_time(String file)const | |
get_sha256(String path)const | |
open_compressed(String path,ModeFlags mode_flags,CompressionMode compression_mode=0) | |
open_encrypted(String path,ModeFlags mode_flags,PoolByteArray key) | |
open_encrypted_with_pass(String path,ModeFlags mode_flags,String pass) | |
void | |
void | |
void | |
void | |
void | |
void | |
void | store_buffer(PoolByteArray buffer) |
void | store_csv_line(PoolStringArray values,String delim=",") |
void | store_double(float value) |
void | store_float(float value) |
void | store_line(String line) |
void | store_pascal_string(String string) |
void | store_real(float value) |
void | store_string(String string) |
void |
Enumerations¶
enumModeFlags:
READ =1 --- Opens the file for read operations. The cursor is positioned at the beginning of the file.
WRITE =2 --- Opens the file for write operations. The file is created if it does not exist, and truncated if it does.
READ_WRITE =3 --- Opens the file for read and write operations. Does not truncate the file. The cursor is positioned at the beginning of the file.
WRITE_READ =7 --- Opens the file for read and write operations. The file is created if it does not exist, and truncated if it does. The cursor is positioned at the beginning of the file.
enumCompressionMode:
Property Descriptions¶
boolendian_swap
Default |
|
Setter | set_endian_swap(value) |
Getter | get_endian_swap() |
Iftrue, the file is read with big-endianendianness. Iffalse, the file is read with little-endian endianness. If in doubt, leave this tofalse as most files are written with little-endian endianness.
Note:endian_swap 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 tofalse whenever you open the file. Therefore, you must setendian_swapafter opening the file, not before.
Method Descriptions¶
voidclose()
Closes the currently opened file and prevents subsequent read/write operations. Useflush to persist the data to disk without closing the file.
Returnstrue 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:
whilefile.get_position()<file.get_len():# Read data
Returnstrue 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. SeeResourceLoader.exists for an alternative approach that takes resource remapping into account.
voidflush()
Writes the file's buffer to disk. Flushing is automatically performed when the file is closed. This means you don't need to callflush manually before closing a file usingclose. Still, callingflush can be used to ensure the data is safe even if the project crashes instead of being closed gracefully.
Note: Only callflush when you actually need it. Otherwise, it will decrease performance due to constant disk writes.
Returns the next 16 bits from the file as an integer. Seestore_16 for details on what values can be stored and retrieved this way.
Returns the next 32 bits from the file as an integer. Seestore_32 for details on what values can be stored and retrieved this way.
Returns the next 64 bits from the file as an integer. Seestore_64 for details on what values can be stored and retrieved this way.
Returns the next 8 bits from the file as an integer. Seestore_8 for details on what values can be stored and retrieved this way.
Returns the whole file as aString.
Text is interpreted as being UTF-8 encoded.
PoolByteArrayget_buffer(int len)const
Returns nextlen bytes of the file as aPoolByteArray.
PoolStringArrayget_csv_line(String delim=",")const
Returns the next value of the file in CSV (Comma-Separated Values) format. You can pass a different delimiterdelim 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!Whatasurprise!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 itcould 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.
Returns the next 64 bits from the file as a floating-point number.
Returns the last error that happened when trying to perform operations. Compare with theERR_FILE_* constants fromError.
Returns the next 32 bits from the file as a floating-point number.
Returns the size of the file in bytes.
Returns the next line of the file as aString.
Text is interpreted as being UTF-8 encoded.
Returns an MD5 String representing the file at the given path or an emptyString on failure.
Returns the last time thefile was modified in unix timestamp format or returns aString "ERROR INfile". This unix timestamp can be converted to datetime by usingOS.get_datetime_from_unix_time.
Stringget_pascal_string()
Returns aString saved in Pascal format from the file.
Text is interpreted as being UTF-8 encoded.
Returns the path as aString for the current open file.
Returns the absolute path as aString for the current open file.
Returns the file cursor's position.
Returns the next bits from the file as a floating-point number.
Returns a SHA-256String representing the file at the given path or an emptyString on failure.
Returns the nextVariant value from the file. Ifallow_objects istrue, 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.
Returnstrue if the file is currently opened.
Opens the file for writing or reading, depending on the flags.
Erroropen_compressed(String path,ModeFlags mode_flags,CompressionMode compression_mode=0)
Opens a compressed file for reading or writing.
Note:open_compressed can only read files that were saved by Godot, not third-party compression formats. SeeGitHub issue #28999 for a workaround.
Erroropen_encrypted(String path,ModeFlags mode_flags,PoolByteArray key)
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.
Opens an encrypted file in write or read mode. You need to pass a password to encrypt/decrypt it.
voidseek(int position)
Changes the file reading/writing cursor to the specified position (in bytes from the beginning of the file).
voidseek_end(int position=0)
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.
voidstore_16(int value)
Stores an integer as 16 bits in the file.
Note: Thevalue should lie in the interval[0,2^16-1]. Any other value will overflow and wrap around.
To store a signed integer, usestore_64 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:
constMAX_15B=1<<15constMAX_16B=1<<16funcunsigned16_to_signed(unsigned):return(unsigned+MAX_15B)%MAX_16B-MAX_15Bfunc_ready():varf=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.varread1=f.get_16()# 65494varread2=f.get_16()# 121varconverted1=unsigned16_to_signed(read1)# -42varconverted2=unsigned16_to_signed(read2)# 121
voidstore_32(int value)
Stores an integer as 32 bits in the file.
Note: Thevalue should lie in the interval[0,2^32-1]. Any other value will overflow and wrap around.
To store a signed integer, usestore_64, or convert it manually (seestore_16 for an example).
voidstore_64(int value)
Stores an integer as 64 bits in the file.
Note: Thevalue must lie in the interval[-2^63,2^63-1] (i.e. be a validint value).
voidstore_8(int value)
Stores an integer as 8 bits in the file.
Note: Thevalue should lie in the interval[0,255]. Any other value will overflow and wrap around.
To store a signed integer, usestore_64, or convert it manually (seestore_16 for an example).
voidstore_buffer(PoolByteArray buffer)
Stores the given array of bytes in the file.
voidstore_csv_line(PoolStringArray values,String delim=",")
Store the givenPoolStringArray in the file as a line formatted in the CSV (Comma-Separated Values) format. You can pass a different delimiterdelim to use other than the default"," (comma). This delimiter must be one-character long.
Text will be encoded as UTF-8.
voidstore_double(float value)
Stores a floating-point number as 64 bits in the file.
voidstore_float(float value)
Stores a floating-point number as 32 bits in the file.
voidstore_line(String line)
Appendsline to the file followed by a line return character (\n), encoding the text as UTF-8.
voidstore_pascal_string(String string)
Stores the givenString 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.
voidstore_real(float value)
Stores a floating-point number in the file.
voidstore_string(String string)
Appendsstring 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 usingstore_pascal_string instead. For retrieving strings from a text file, you can useget_buffer(length).get_string_from_utf8() (if you know the length) orget_as_text.
Stores any Variant value in the file. Iffull_objects istrue, encoding objects is allowed (and can potentially include code).
Note: Not all properties are included. Only properties that are configured with the@GlobalScope.PROPERTY_USAGE_STORAGE flag set will be serialized. You can add a new usage flag to a property by overriding theObject._get_property_list method in your class. You can also check how property usage is configured by callingObject._get_property_list. SeePropertyUsageFlags for the possible usage flags.