Posts: How to Set the Default Program to Open Files on Windows Using Python

Published 2026-01-20 01:00 Updated 2026-01-20 12:00 745 words 4 min read

kissablecho avatar

kissablecho

Kissablecho's personal blog — recording life, sharing technology, anime & white stockings enthusiast.

This Python tool is used to set the default program for opening files in Windows system settings. It modifies file associations via command line and registry methods, compatible with Windows 7, 10, and 11.

Translated by AI model Qwen/Qwen3-8B.

Source Language: Simplified Chinese, Target Language: english, Translation Time: 2026-05-01 02:39

.

AI translation is for reference only. Accuracy is not guaranteed, please refer to the original text.

Introduction

I am the class-appointed IT committee member (a burdensome duty), due to the teaching needs of the class, I need to switch to a specific player on a particular day.

I wanted to use Python to automate the setting of the default program for MP4 files, and then I ran the code generated by DeepSeek and other assistants. However, I was stuck by various strange errors. In desperation, I looked for related code on Github.

Fortunately, I really found a Python-written "File Default Master" software on Github, thank you to the original author.

https://github.com/3089464667/default-app

I then read through the code and extracted the core code for setting the default program.

Code Explanation

This code is a Python tool for setting the default program for file types on Windows systems. It modifies the association through command line and registry, and is applicable to Windows 7/10/11.

Core Features

  • Set default application: The set_default_app() function specifies the file extension and the corresponding application path, and can automatically configure system associations.
  • Compatibility handling: Prioritizes using assoc and ftype command line settings, directly modifies the registry, and handles the user selection verification mechanism in Windows 10/11.
  • Verification function: The check_default_app() can check whether the current default application is the specified one.

Usage Example

set_default_app(".txt", "C:\\Windows\\notepad.exe")
if check_default_app(".txt", "C:\\Windows\\notepad.exe"):
    print("设置成功")

Full Code

import winreg
import subprocess
import os
import time
import hashlib

def set_default_app_cmd(file_extension, app_path):
    """
    使用 Windows 命令行工具设置默认打开程序,兼容 Windows 10/11
    """
    try:
        ext = file_extension if file_extension.startswith('.') else '.' + file_extension
        prog_id = ext[1:].upper() + "File"
        subprocess.run(f'assoc {ext}={prog_id}', shell=True, check=True)
        subprocess.run(f'ftype {prog_id}="{app_path}" "%1"', shell=True, check=True)
        return True, ""
    except Exception as e:
        return False, str(e)

def set_default_app(file_extension, app_path, icon_path=None):
    """
    设置文件扩展名的默认打开程序
    参数:
        file_extension: 文件扩展名(如 ".txt" 或 "txt")
        app_path: 应用程序完整路径
        icon_path: 可选图标路径
    返回: 无
    """
    # 先用命令行设置
    ok, msg = set_default_app_cmd(file_extension, app_path)
    if not ok:
        print(f"命令行设置失败: {msg}")
    
    try:
        # 确保扩展名格式正确
        ext = file_extension if file_extension.startswith('.') else '.' + file_extension
        
        # 创建或打开扩展名对应的注册表键
        with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, ext) as key:
            prog_id = winreg.QueryValue(key, None)
            if not prog_id:
                prog_id = ext[1:].upper() + "File"
                winreg.SetValue(key, None, winreg.REG_SZ, prog_id)
            
            # 设置打开命令
            with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, f"{prog_id}\\shell\\open\\command") as cmd_key:
                winreg.SetValue(cmd_key, None, winreg.REG_SZ, f"\"{app_path}\" \"%1\"")
        
        # 处理用户选择(Windows 10/11 需要)
        user_choice_path = f"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\{ext}\\"
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, user_choice_path, 0, winreg.KEY_ALL_ACCESS) as key:
                winreg.DeleteKey(key, "UserChoice")
        except WindowsError:
            pass
        
        # 生成用户选择哈希(Windows 10/11 验证机制)
        try:
            user_sid = os.getlogin()
        except Exception:
            user_sid = "unknown"
        
        timestamp = int(time.time())
        hash_input = f"{prog_id}{user_sid}{timestamp}".encode('utf-16le')
        hash_value = hashlib.sha256(hash_input).hexdigest()
        
        with winreg.CreateKey(winreg.HKEY_CURRENT_USER, user_choice_path + "UserChoice") as key:
            winreg.SetValueEx(key, "ProgId", 0, winreg.REG_SZ, prog_id)
            winreg.SetValueEx(key, "Hash", 0, winreg.REG_SZ, hash_value)
        
        print(f"成功设置 {ext} 的默认打开程序为: {app_path}")
        
    except Exception as e:
        print(f"设置默认程序失败: {e}")

def check_default_app(file_extension, app_path):
    """
    检查当前扩展名的默认打开程序是否为指定程序
    参数:
        file_extension: 文件扩展名
        app_path: 应用程序路径
    返回: True/False
    """
    ext = file_extension if file_extension.startswith('.') else '.' + file_extension
    try:
        output = subprocess.check_output(f"assoc {ext}", shell=True, encoding="gbk", errors="ignore")
        if "=" not in output:
            return False
        prog_id = output.strip().split("=")[-1]
        output2 = subprocess.check_output(f"ftype {prog_id}", shell=True, encoding="gbk", errors="ignore")
        if app_path.lower() in output2.lower():
            return True
    except Exception:
        pass
    return False

# 使用示例
if __name__ == "__main__":
    # 示例1:设置.txt文件用记事本打开
    set_default_app(".txt", "C:\\Windows\\notepad.exe")
    
    # 示例2:设置.jpg文件用照片查看器打开
    set_default_app("jpg", "C:\\Windows\\System32\\rundll32.exe", "C:\\Windows\\System32\\photo_viewer.dll")
    
    # 检查设置是否成功
    if check_default_app(".txt", "C:\\Windows\\notepad.exe"):
        print("设置成功!")
    else:
        print("设置失败!")

If you enjoyed this, leave a comment~