jiahuajing 发表于 2026-8-12 17:25:54

用Python写的一个脚本,机床拷贝的文件ALL-PROG.TXT分割成独立的NC文件

# -*- coding: utf-8 -*-
"""
NC/G代码文件分割工具
- 以 OXXXX 开头,以 M30 结束
- 每个分割文件以该程序第一行的字符作为文件名
"""

import os
import re


def sanitize_filename(name: str) -> str:
    """清理文件名中的非法字符(Windows 不允许 \ / : * ? " < > |)"""
    # 替换非法字符为下划线
    name = re.sub(r'[\\/:*?"<>|]', '_', name)
    # 去除首尾空白和点
    name = name.strip(' .')
    # 限制长度,避免文件名过长
    return name[:100] if name else 'unnamed'


def split_nc_file(input_path: str, output_dir: str = None) -> list:
    # 默认输出目录:输入文件同目录下的 split_output
    if output_dir is None:
      output_dir = os.path.join(os.path.dirname(os.path.abspath(input_path)), 'split_output')
    os.makedirs(output_dir, exist_ok=True)

    # 多编码兼容读取
    content = None
    for enc in ('utf-8', 'gbk', 'gb2312', 'latin-1'):
      try:
            with open(input_path, 'r', encoding=enc) as f:
                content = f.read()
            break
      except UnicodeDecodeError:
            continue
    if content is None:
      raise ValueError("无法识别文件编码")

    lines = content.splitlines()
    generated = []

    current_lines = []
    first_line = None
    in_program = False

    for line in lines:
      stripped = line.strip()

      # 检测程序开始:行首 O + 数字
      if re.match(r'^O\d+', stripped, re.IGNORECASE):
            in_program = True
            current_lines =
            first_line = stripped   # 记录第一行(去掉首尾空白)
            continue

      if in_program:
            current_lines.append(line)

            # 检测程序结束:行中包含 M30
            if re.search(r'M30', stripped, re.IGNORECASE):
                # 用第一行字符作为文件名
                filename = sanitize_filename(first_line) + '.nc'
                out_path = os.path.join(output_dir, filename)

                # 处理重名:自动加序号
                counter = 1
                while os.path.exists(out_path):
                  name, ext = os.path.splitext(filename)
                  out_path = os.path.join(output_dir, f"{name}_{counter}{ext}")
                  counter += 1

                # 写入文件
                with open(out_path, 'w', encoding='utf-8') as f:
                  f.write('\n'.join(current_lines) + '\n')

                generated.append(out_path)
                print(f"已生成: {out_path}")

                # 重置状态
                in_program = False
                current_lines = []
                first_line = None

    return generated


if __name__ == '__main__':
    path = input("请输入文件路径: ").strip().strip('"')
    if not os.path.isfile(path):
      print(f"文件不存在: {path}")
    else:
      results = split_nc_file(path)
      print(f"\n分割完成,共生成 {len(results)} 个文件。")

wang_fanuc 发表于 2026-8-13 08:15:29

虽然看不懂,感谢分享!

daike170 发表于 2026-8-13 08:26:09

感谢分享!!!!

吴小均 发表于 2026-8-13 09:17:16

虽然看不懂,感谢分享!

chiouho 发表于 2026-8-13 09:23:08

感谢分享

xinruyu369 发表于 2026-8-13 10:00:04

针对老机床储存空间小的情况,这个好用

zyz0907 发表于 2026-8-13 13:37:11

虽然看不懂,感谢分享!

dongdong536 发表于 2026-8-13 18:36:02

虽然看不懂,感谢分享!!!!

309494778 发表于 2026-8-14 10:03:15

感谢大佬分享

孟令智 发表于 2026-8-17 14:24:18

感谢分享,楼主大才。
页: [1]
查看完整版本: 用Python写的一个脚本,机床拷贝的文件ALL-PROG.TXT分割成独立的NC文件