Skip to content

GLib.KeyFile

record (struct)

GKeyFile parses .ini-like config files.

GKeyFile lets you parse, edit or create files containing groups of key-value pairs, which we call ‘key files’ for lack of a better name. Several freedesktop.org specifications use key files. For example, the Desktop Entry Specification and the Icon Theme Specification.

The syntax of key files is described in detail in the Desktop Entry Specification, here is a quick summary: Key files consists of groups of key-value pairs, interspersed with comments.

# this is just an example
# there can be comments before the first group

[First Group]

Name=Key File Example\tthis value shows\nescaping

# localized strings are stored in multiple key-value pairs
Welcome=Hello
Welcome[de]=Hallo
Welcome[fr_FR]=Bonjour
Welcome[it]=Ciao

[Another Group]

Numbers=2;20;-200;0

Booleans=true;false;true;true

Lines beginning with a # and blank lines are considered comments.

Groups are started by a header line containing the group name enclosed in [ and ], and ended implicitly by the start of the next group or the end of the file. Each key-value pair must be contained in a group.

Key-value pairs generally have the form key=value, with the exception of localized strings, which have the form key[locale]=value, with a locale identifier of the form lang_COUNTRY@MODIFIER where COUNTRY and MODIFIER are optional. As a special case, the locale C is associated with the untranslated pair key=value (since GLib 2.84). Space before and after the = character is ignored. Newline, tab, carriage return and backslash characters in value are escaped as \n, \t, \r, and \\\\, respectively. To preserve leading spaces in values, these can also be escaped as \s.

Key files can store strings (possibly with localized variants), integers, booleans and lists of these. Lists are separated by a separator character, typically ; or ,. To use the list separator character in a value in a list, it has to be escaped by prefixing it with a backslash.

This syntax is obviously inspired by the .ini files commonly met on Windows, but there are some important differences:

  • .ini files use the ; character to begin comments, key files use the # character.

  • Key files do not allow for ungrouped keys meaning only comments can precede the first group.

  • Key files are always encoded in UTF-8.

  • Key and Group names are case-sensitive. For example, a group called [GROUP] is a different from [group].

  • .ini files don’t have a strongly typed boolean entry type, they only have GetProfileInt(). In key files, only true and false (in lower case) are allowed.

Note that in contrast to the Desktop Entry Specification, groups in key files may contain the same key multiple times; the last entry wins. Key files may also contain multiple groups with the same name; they are merged together. Another difference is that keys and group names in key files are not restricted to ASCII characters.

Here is an example of loading a key file and reading a value:

g_autoptr(GError) error = NULL;
g_autoptr(GKeyFile) key_file = g_key_file_new ();

if (!g_key_file_load_from_file (key_file, "key-file.ini", flags, &error))
  {
    if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
      g_warning ("Error loading key file: %s", error->message);
    return;
  }

g_autofree gchar *val = g_key_file_get_string (key_file, "Group Name", "SomeKey", &error);
if (val == NULL &&
    !g_error_matches (error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND))
  {
    g_warning ("Error finding key in key file: %s", error->message);
    return;
  }
else if (val == NULL)
  {
    // Fall back to a default value.
    val = g_strdup ("default-value");
  }

Here is an example of creating and saving a key file:

g_autoptr(GKeyFile) key_file = g_key_file_new ();
const gchar *val = ;
g_autoptr(GError) error = NULL;

g_key_file_set_string (key_file, "Group Name", "SomeKey", val);

// Save as a file.
if (!g_key_file_save_to_file (key_file, "key-file.ini", &error))
  {
    g_warning ("Error saving key file: %s", error->message);
    return;
  }

// Or store to a GBytes for use elsewhere.
gsize data_len;
g_autofree guint8 *data = (guint8 *) g_key_file_to_data (key_file, &data_len, &error);
if (data == NULL)
  {
    g_warning ("Error saving key file: %s", error->message);
    return;
  }
g_autoptr(GBytes) bytes = g_bytes_new_take (g_steal_pointer (&data), data_len);

Constructors

new

@classmethod
def new(cls) -> KeyFile

Creates a new empty KeyFile object.

Use KeyFile.load_from_file, KeyFile.load_from_data, KeyFile.load_from_dirs or KeyFile.load_from_data_dirs to read an existing key file.

Methods

get_boolean

def get_boolean(self, group_name: str, key: str) -> bool

Returns the value associated with key under group_name as a boolean.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. Likewise, if the value associated with key cannot be interpreted as a boolean then KeyFileError.INVALID_VALUE is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_boolean_list

def get_boolean_list(self, group_name: str, key: str) -> list[bool]

Returns the values associated with key under group_name as booleans.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. Likewise, if the values associated with key cannot be interpreted as booleans then KeyFileError.INVALID_VALUE is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_comment

def get_comment(self, group_name: str | None = ..., key: str | None = ...) -> str

Retrieves a comment above key from group_name.

If key is NULL then comment will be read from above group_name. If both key and group_name are NULL, then comment will be read from above the first group in the file.

Note that the returned string does not include the # comment markers, but does include any whitespace after them (on each line). It includes the line breaks between lines, but does not include the final line break.

Parameters:

  • group_name — a group name, or NULL to get a top-level comment
  • key — a key, or NULL to get a group comment

get_double

def get_double(self, group_name: str, key: str) -> float

Returns the value associated with key under group_name as a double.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. Likewise, if the value associated with key cannot be interpreted as a double then KeyFileError.INVALID_VALUE is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_double_list

def get_double_list(self, group_name: str, key: str) -> list[float]

Returns the values associated with key under group_name as doubles.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. Likewise, if the values associated with key cannot be interpreted as doubles then KeyFileError.INVALID_VALUE is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_groups

def get_groups(self) -> tuple[list[str], int]

Returns all groups in the key file loaded with key_file.

The array of returned groups will be NULL-terminated, so length may optionally be NULL.

get_int64

def get_int64(self, group_name: str, key: str) -> int

Returns the value associated with key under group_name as a signed 64-bit integer.

This is similar to KeyFile.get_integer but can return 64-bit results without truncation.

Parameters:

  • group_name — a group name
  • key — a key

get_integer

def get_integer(self, group_name: str, key: str) -> int

Returns the value associated with key under group_name as an integer.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. Likewise, if the value associated with key cannot be interpreted as an integer, or is out of range for a gint, then KeyFileError.INVALID_VALUE is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_integer_list

def get_integer_list(self, group_name: str, key: str) -> list[int]

Returns the values associated with key under group_name as integers.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. Likewise, if the values associated with key cannot be interpreted as integers, or are out of range for gint, then KeyFileError.INVALID_VALUE is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_keys

def get_keys(self, group_name: str) -> tuple[list[str], int]

Returns all keys for the group name group_name.

The array of returned keys will be NULL-terminated, so length may optionally be NULL. If the group_name cannot be found, KeyFileError.GROUP_NOT_FOUND is returned.

Parameters:

  • group_name — a group name

get_locale_for_key

def get_locale_for_key(self, group_name: str, key: str, locale: str | None = ...) -> str | None

Returns the actual locale which the result of KeyFile.get_locale_string or KeyFile.get_locale_string_list came from.

If calling KeyFile.get_locale_string or KeyFile.get_locale_string_list with exactly the same key_file, group_name, key and locale, the result of those functions will have originally been tagged with the locale that is the result of this function.

Parameters:

  • group_name — a group name
  • key — a key
  • locale — a locale identifier or NULL to use the current locale

get_locale_string

def get_locale_string(self, group_name: str, key: str, locale: str | None = ...) -> str

Returns the value associated with key under group_name translated in the given locale if available.

If locale is C then the untranslated value is returned (since GLib 2.84).

If locale is NULL then the current locale is assumed.

If locale is to be non-NULL, or if the current locale will change over the lifetime of the KeyFile, it must be loaded with KeyFileFlags.KEEP_TRANSLATIONS in order to load strings for all locales.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. If the value associated with key cannot be interpreted or no suitable translation can be found then the untranslated value is returned.

Parameters:

  • group_name — a group name
  • key — a key
  • locale — a locale identifier or NULL to use the current locale

get_locale_string_list

def get_locale_string_list(self, group_name: str, key: str, locale: str | None = ...) -> list[str]

Returns the values associated with key under group_name translated in the given locale if available.

If locale is C then the untranslated value is returned (since GLib 2.84).

If locale is NULL then the current locale is assumed.

If locale is to be non-NULL, or if the current locale will change over the lifetime of the KeyFile, it must be loaded with KeyFileFlags.KEEP_TRANSLATIONS in order to load strings for all locales.

If key cannot be found then KeyFileError.KEY_NOT_FOUND is returned. If the values associated with key cannot be interpreted or no suitable translations can be found then the untranslated values are returned. The returned array is NULL-terminated, so length may optionally be NULL.

Parameters:

  • group_name — a group name
  • key — a key
  • locale — a locale identifier or NULL to use the current locale

get_start_group

def get_start_group(self) -> str | None

Returns the name of the start group of the file.

get_string

def get_string(self, group_name: str, key: str) -> str

Returns the string value associated with key under group_name.

Unlike KeyFile.get_value, this function handles escape sequences like \s.

If the key cannot be found, KeyFileError.KEY_NOT_FOUND is returned. If the group_name cannot be found, KeyFileError.GROUP_NOT_FOUND is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_string_list

def get_string_list(self, group_name: str, key: str) -> list[str]

Returns the values associated with key under group_name.

If the key cannot be found, KeyFileError.KEY_NOT_FOUND is returned. If the group_name cannot be found, KeyFileError.GROUP_NOT_FOUND is returned.

Parameters:

  • group_name — a group name
  • key — a key

get_uint64

def get_uint64(self, group_name: str, key: str) -> int

Returns the value associated with key under group_name as an unsigned 64-bit integer.

This is similar to KeyFile.get_integer but can return large positive results without truncation.

Parameters:

  • group_name — a group name
  • key — a key

get_value

def get_value(self, group_name: str, key: str) -> str

Returns the raw value associated with key under group_name.

Use KeyFile.get_string to retrieve an unescaped UTF-8 string.

If the key cannot be found, KeyFileError.KEY_NOT_FOUND is returned. If the group_name cannot be found, KeyFileError.GROUP_NOT_FOUND is returned.

Parameters:

  • group_name — a group name
  • key — a key

has_group

def has_group(self, group_name: str) -> bool

Looks whether the key file has the group group_name.

Parameters:

  • group_name — a group name

load_from_bytes

def load_from_bytes(self, bytes: Bytes, flags: KeyFileFlags | int) -> bool

Loads a key file from the data in bytes into an empty KeyFile structure.

If the object cannot be created then a KeyFileError is returned.

Parameters:

load_from_data

def load_from_data(self, data: str, length: int, flags: KeyFileFlags | int) -> bool

Loads a key file from memory into an empty KeyFile structure.

If the object cannot be created then a [errorGLib.KeyFileError is returned.

Parameters:

  • data — key file loaded in memory
  • length — the length of data in bytes (or (gsize)-1 if data is nul-terminated)
  • flags — flags from KeyFileFlags

load_from_data_dirs

def load_from_data_dirs(self, file: str | bytes | os.PathLike[str] | os.PathLike[bytes], flags: KeyFileFlags | int) -> tuple[bool, str]

Looks for a key file named file in the paths returned from get_user_data_dir and get_system_data_dirs.

The search algorithm from KeyFile.load_from_dirs is used. If file is found, it’s loaded into key_file and its full path is returned in full_path.

If the file could not be loaded then either a FileError or KeyFileError is returned.

Parameters:

  • file — a relative path to a filename to open and parse
  • flags — flags from KeyFileFlags

load_from_dirs

def load_from_dirs(self, file: str | bytes | os.PathLike[str] | os.PathLike[bytes], search_dirs: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], flags: KeyFileFlags | int) -> tuple[bool, str]

Looks for a key file named file in the paths specified in search_dirs, loads the file into key_file and returns the file’s full path in full_path.

search_dirs are checked in the order listed in the array, with the highest priority directory listed first. Within each directory, file is looked for. If it’s not found, - characters in file are progressively replaced with directory separators to search subdirectories of the search directory. If the file has not been found after all - characters have been replaced, the next search directory in search_dirs is checked.

If the file could not be found in any of the search_dirs, KeyFileError.NOT_FOUND is returned. If the file is found but the OS returns an error when opening or reading the file, a FileError is returned. If there is a problem parsing the file, a KeyFileError is returned.

Parameters:

  • file — a relative path to a filename to open and parse
  • search_dirsNULL-terminated array of directories to search
  • flags — flags from KeyFileFlags

load_from_file

def load_from_file(self, file: str | bytes | os.PathLike[str] | os.PathLike[bytes], flags: KeyFileFlags | int) -> bool

Loads a key file into an empty KeyFile structure.

If the OS returns an error when opening or reading the file, a FileError is returned. If there is a problem parsing the file, a KeyFileError is returned.

This function will never return a KeyFileError.NOT_FOUND error. If the file is not found, FileError.NOENT is returned.

Parameters:

  • file — the path of a filename to load, in the GLib filename encoding
  • flags — flags from KeyFileFlags

remove_comment

def remove_comment(self, group_name: str | None = ..., key: str | None = ...) -> bool

Removes a comment above key from group_name.

If key is NULL then comment will be removed above group_name. If both key and group_name are NULL, then comment will be removed above the first group in the file.

Parameters:

  • group_name — a group name, or NULL to get a top-level comment
  • key — a key, or NULL to get a group comment

remove_group

def remove_group(self, group_name: str) -> bool

Removes the specified group, group_name, from the key file.

Parameters:

  • group_name — a group name

remove_key

def remove_key(self, group_name: str, key: str) -> bool

Removes key in group_name from the key file.

Parameters:

  • group_name — a group name
  • key — a key name to remove

save_to_file

def save_to_file(self, filename: str) -> bool

Writes the contents of key_file to filename using file_set_contents.

If you need stricter guarantees about durability of the written file than are provided by file_set_contents, use file_set_contents_full with the return value of KeyFile.to_data.

This function can fail for any of the reasons that file_set_contents may fail.

Parameters:

  • filename — the name of the file to write to

set_boolean

def set_boolean(self, group_name: str, key: str, value: bool) -> None

Associates a new boolean value with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • value — true or false

set_boolean_list

def set_boolean_list(self, group_name: str, key: str, list: list[bool]) -> None

Associates a list of boolean values with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • list — an array of boolean values

set_comment

def set_comment(self, group_name: str | None, key: str | None, comment: str) -> bool

Places a comment above key from group_name.

If key is NULL then comment will be written above group_name. If both key and group_name are NULL, then comment will be written above the first group in the file.

Passing a non-existent group_name or key to this function returns false and populates error. (In contrast, passing a non-existent group_name or key to KeyFile.set_string creates the associated group name and key.)

Note that this function prepends a # comment marker to each line of comment.

Parameters:

  • group_name — a group name, or NULL to write a top-level comment
  • key — a key, or NULL to write a group comment
  • comment — a comment

set_double

def set_double(self, group_name: str, key: str, value: float) -> None

Associates a new double value with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • value — a double value

set_double_list

def set_double_list(self, group_name: str, key: str, list: list[float]) -> None

Associates a list of double values with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • list — an array of double values

set_int64

def set_int64(self, group_name: str, key: str, value: int) -> None

Associates a new integer value with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • value — an integer value

set_integer

def set_integer(self, group_name: str, key: str, value: int) -> None

Associates a new integer value with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • value — an integer value

set_integer_list

def set_integer_list(self, group_name: str, key: str, list: list[int]) -> None

Associates a list of integer values with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • list — an array of integer values

set_list_separator

def set_list_separator(self, separator: int) -> None

Sets the character which is used to separate values in lists.

Typically ; or , are used as separators. The default list separator is ;.

Parameters:

  • separator — the separator

set_locale_string

def set_locale_string(self, group_name: str, key: str, locale: str, string: str) -> None

Associates a string value for key and locale under group_name.

If the translation for key cannot be found then it is created.

If locale is C then the untranslated value is set (since GLib 2.84).

Parameters:

  • group_name — a group name
  • key — a key
  • locale — a locale identifier
  • string — a string

set_locale_string_list

def set_locale_string_list(self, group_name: str, key: str, locale: str, list: list[str]) -> None

Associates a list of string values for key and locale under group_name.

If locale is C then the untranslated value is set (since GLib 2.84).

If the translation for key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • locale — a locale identifier
  • list — a NULL-terminated array of locale string values

set_string

def set_string(self, group_name: str, key: str, string: str) -> None

Associates a new string value with key under group_name.

If key cannot be found then it is created. If group_name cannot be found then it is created. Unlike KeyFile.set_value, this function handles characters that need escaping, such as newlines.

Parameters:

  • group_name — a group name
  • key — a key
  • string — a string

set_string_list

def set_string_list(self, group_name: str, key: str, list: list[str]) -> None

Associates a list of string values for key under group_name.

If key cannot be found then it is created. If group_name cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • list — an array of string values

set_uint64

def set_uint64(self, group_name: str, key: str, value: int) -> None

Associates a new integer value with key under group_name.

If key cannot be found then it is created.

Parameters:

  • group_name — a group name
  • key — a key
  • value — an integer value

set_value

def set_value(self, group_name: str, key: str, value: str) -> None

Associates a new value with key under group_name.

If key cannot be found then it is created. If group_name cannot be found then it is created. To set an UTF-8 string which may contain characters that need escaping (such as newlines or spaces), use KeyFile.set_string.

Parameters:

  • group_name — a group name
  • key — a key
  • value — a string

to_data

def to_data(self) -> tuple[str, int]

Outputs key_file as a string.

Note that this function never reports an error.

unref

def unref(self) -> None

Decreases the reference count of key_file by 1.

If the reference count reaches zero, frees the key file and all its allocated memory.

Static functions

error_quark

@staticmethod
def error_quark() -> Quark