Python Read and Write Windows Registry: A Step Guide – Python Tutorial

By | April 19, 2021

Somtimes, we need write and read some information in windows registry. In this tutorial, we will intorduce you how to do using winreg library.

Preliminary

We should import winreg library.

import winreg

We should notice: windows registry is organized as a tree structure.

the structure of windows registry

In order to write and read information from registry, we should notice the key.

Write information to windows registry

In this example, we will write some information in HKEY_CURRENT_USER.

Here is an example:

path = winreg.HKEY_CURRENT_USER

def save_reg(k = 'pdfpagespliter', v = 0):
    try:
        key = winreg.OpenKeyEx(path, r"SOFTWARE\\")
        newKey = winreg.CreateKey(key,"ByteBash")
        winreg.SetValueEx(newKey, k, 0, winreg.REG_SZ, str(v))
        if newKey:
            winreg.CloseKey(newKey)
        return True
    except Exception as e:
        print(e)
    return False

In this example, we will write {pdfpagespliter: 0}  in HKEY_CURRENT_USER\SOFTWARE\ByteBash

ByteBash does not exist in HKEY_CURRENT_USER\SOFTWARE\, we will create it using winreg.CreateKey() firstly.

Then will use winreg.SetValueEx() to write key and its value.

Run this function, you will find this result.

python write value to windows registry

Read information from windows registry

We also will write a function to read information from windows registry.

Here is an example:

def read_reg(k = 'pdfpagespliter'):
    try:
        key = winreg.OpenKeyEx(path, r"SOFTWARE\\ByteBash\\")
        value = winreg.QueryValueEx(key,k)
        if key:
            winreg.CloseKey(key)
        return value[0]
    except Exception as e:
        print(e)
    return None

In order to read information from windows registry, we should open a key and read value.

The core code is:

value = winreg.QueryValueEx(key,k)

You should notice: the value is in 0 index of value.

Leave a Reply