What is winreg.CreateKey in Python?

Share

winreg (Windows Registry API) provides functions to expose the Windows Registry API to python. We use this module expose a low-level interface to the registry.

CreateKey

The method CreateKey either creates a new key or opens an existing key. The method takes both key, sub_key as parameters.

Syntax

winreg.CreateKey(key, sub_key)

Parameters

key: Any open HKEY_* constant or one of the predefined HKEY_* constants can be given as a parameter to the method.

sub_key: This is the subkey of any given key. It is a string value. This parameter cannot be None. However, if a user is using any predefined keys, this parameter can have the value None.

In the case of an existing key being passed to the method, the function simply opens the key mentioned. Then, there is no need to create a new key.

Return value

This function returns the handle of the opened key. An OSError exception is raised in case of a failure to execute this function.

Code

Let’s have a look at the code for using CreateKey to open a predefined or existing key. This function calls the winreg.FlushKey using one of the open keys reg.HKEY_CURRENT_USER as one of the parameters and any subkeys that belong to the Keys.

import winreg as reg
key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk')
Copyright ©2024 Educative, Inc. All rights reserved