import _winreg import re from os import listdir import ctypes wallDir = 'c:\\wallpaper\\'; wallPaperLocation = ('Control Panel\\Desktop') key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, wallPaperLocation, 0, _winreg.KEY_ALL_ACCESS) files = [] for file in listdir(wallDir): g = re.match("^.+\.jpg$", file, re.IGNORECASE) if g: files.append(file) v = _winreg.QueryValueEx(key, 'WallPaper') print v[0] g = re.match("^.+\\\(.+)$", v[0]) oldname = "" if g: oldname = g.group(1) else: print "No Match" sys.exit(1) print oldname print files if len(files) > 0: #find idx of old name oidx = -1 n = 0 for file in files: if file == oldname: oidx = n break else: n += 1 idx = 0 if oidx >= 0: idx = (oidx + 1) % len(files) print "Setting" ctypes.windll.user32.SystemParametersInfoA(20, 0, wallDir + files[idx], 0) _winreg.SetValueEx(key, 'WallPaper', 0, _winreg.REG_SZ, wallDir + files[idx]) _winreg.FlushKey(key) _winreg.CloseKey(key)