File:open([mode], [encoding]) method

Open the file for read/write operations.

Parameters

mode

An optional string that indicates the kind of access when opening the file.

  • "read": the file will be opened for read operations, it's the default if neither mode nor encoding are specified.
  • "write": the file will be opened for write operations, erasing any data already present.
  • "append": the file will be opened for write operations, keeping the current data and starting writing at the end.
  • "readwrite": the file will be opened for read and write operations.

encoding

An optional string that indicates the encoding for read/write operations. By default, encoding is autodetected using Byte Mark Order (BOM) if not provided.

  • "binary" encoding : the file has no encoding, using raw bytes for read/write operations.
  • "utf8" encoding : the File is UTF8 encoded, using UTF8 characters for read/write operations.
  • "unicode" encoding : the File is UNICODE (UCS-2 LE) encoded, using UNICODE characters for read/write operations.
In "write" mode, Byte Order Mark (BOM) is written to the file when "utf8" or "unicode" encoding is provided.

Return value

Returns the same File value if the operation succeeded or raises an error.

Example

local file = sys.File("Hello.txt") -- open the file for writing, using default "binary" encoding file:open("write") file:write("Hello World") file:close()