You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python宏修改已有.slddrw文件的文件属性?

Modifying SolidWorks File Properties with Python

Even though VB/C# are the go-to languages for official SolidWorks automation, you can absolutely tweak file properties using Python via COM interop. Here’s a straightforward, actionable guide to get you up and running:

Prerequisites

  • Install the pywin32 library (this lets Python talk to SolidWorks’ COM API):
    pip install pywin32
    
  • Make sure SolidWorks is installed on your machine (the script can connect to a running instance or launch it automatically).

Step-by-Step Script Example

This script connects to SolidWorks, opens an existing file, updates both custom properties and built-in summary details (like creator and creation time), then saves the changes.

import win32com.client
import datetime

def modify_solidworks_properties(file_path):
    # Connect to SolidWorks application
    sw_app = win32com.client.Dispatch("SldWorks.Application")
    sw_app.Visible = True  # Show SolidWorks window (optional but helpful for debugging)

    # Open the target document (suppress pop-up prompts)
    sw_doc = sw_app.OpenDoc6(
        file_path,
        1,  # Use 1 for parts, 2 for assemblies, 3 for drawings
        1,  # Silent open mode
        "",
        0,
        0
    )

    if not sw_doc:
        print(f"Failed to open file: {file_path}")
        return

    # --------------------------
    # Update Custom Properties
    # --------------------------
    # Get document-level custom property manager (empty string = document-wide)
    custom_prop_mgr = sw_doc.GetCustomPropertyManager("")
    
    # Update an existing custom property
    result = custom_prop_mgr.Set2("Project ID", "PROJ-2024-001", False, "")
    if result == 0:
        print("Successfully updated 'Project ID'")
    
    # Add a new custom property
    result = custom_prop_mgr.Set2("Last Modified By", "Your Name", False, "")
    if result == 0:
        print("Successfully added 'Last Modified By'")

    # --------------------------
    # Modify Built-in Summary Properties
    # --------------------------
    summary_info = sw_doc.SummaryInfo
    
    # Set document author (uses swSumInfoAuthor constant, index = 3)
    summary_info.SetSummaryInfo(3, "Jane Smith")
    print("Updated document author")
    
    # Set new creation date (uses swSumInfoCreationDate constant, index =4)
    new_creation_date = datetime.datetime(2024, 6, 15)
    summary_info.SetSummaryInfo(4, new_creation_date)
    print("Updated creation date")

    # Save changes silently
    save_result = sw_doc.Save3(1, 0, 0)
    if save_result == 0:
        print("All changes saved successfully")
    else:
        print(f"Save failed: Error code {save_result}")

    # Clean up
    sw_app.CloseDoc(file_path)
    # sw_app.Exit()  # Uncomment to close SolidWorks when done

# Replace with your actual file path (use raw string to avoid escape issues)
modify_solidworks_properties(r"C:\Your\File\Path\example_part.sldprt")

Key Details to Keep in Mind

  • File Types: Adjust the second parameter in OpenDoc6 to match your file: 1 for parts, 2 for assemblies, 3 for drawings.
  • Configuration-Specific Properties: To edit properties for a specific configuration, pass the config name to GetCustomPropertyManager (e.g., sw_doc.GetCustomPropertyManager("Default")).
  • Error Handling: The script has basic checks, but you can add try/except blocks to catch COM exceptions (like file not found, read-only locks).
  • Summary Info Indexes: Use these common indexes for built-in properties:
    • 3 = Author (creator)
    • 4 = Creation Date
    • 5 = Last Saved Date
    • 6 = Last Saved By

Troubleshooting Tips

  • If the script can’t connect to SolidWorks, try sw_app = win32com.client.DispatchEx("SldWorks.Application") to launch a new instance in the background.
  • Double-check your file path uses a raw string (r"...") to avoid issues with backslashes.
  • If you get permission errors, ensure the file isn’t open in another app or marked as read-only.

内容的提问来源于stack exchange,提问作者user10552311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:56:46