一个Python脚本,将CST Studio导出的1D数据的txt文件转换为与Ansys HFSS的CSV相同的格式

前言

本文含有AI生成的代码。

这个CST居然不能导出CSV,有点匪夷所思了,只好用Copilot辅助编写一个脚本转换格式,方便导入到之前写的画图程序中。

使用方法

  • 保存本文代码到一个.py文件,如txt2csv_dragdrop.py
  • 将.py文件设置为默认使用Python打开。
  • 将.txt 文件拖拽到它上面,程序将生成同名.csv文件。
# txt2csv_dragdrop.py
# 说明:Windows 下可将 .txt 拖拽到该 .py 文件上运行,自动输出同名 .csv
import csv
import os
import sys

header_dict = {
    "Frequency / GHz": "Freq [GHz]",
    "Realized Gain": "dB(RealizedGainTotal) []",
    "S1,1 [Magnitude / dB]": "dB(S(1,1)) []",
}


def parse_txt_to_rows(path: str):
    header = None
    rows = []

    with open(path, "r", encoding="utf-8", errors="ignore") as f:
        for line in f:
            s = line.strip()
            if not s:
                continue

            # 注释/表头行:以 # 开头
            if s.startswith("#"):
                # 形如:#"Frequency / GHz"  "Realized Gain,..."
                if '"' in s:
                    parts = []
                    cur = ""
                    in_q = False
                    for ch in s:
                        if ch == '"':
                            in_q = not in_q
                            if not in_q and cur != "":
                                for k, v in header_dict.items():
                                    if cur.startswith(k):
                                        cur = v
                                        break
                                parts.append(cur)
                                cur = ""
                        elif in_q:
                            cur += ch
                    if len(parts) >= 2:
                        header = parts[:2]
                continue

            # 数据行:两列,空白或 tab 分隔
            parts = s.split()
            if len(parts) < 2:
                continue
            try:
                x = float(parts[0])
                y = float(parts[1])
            except ValueError:
                continue
            rows.append((x, y))

    if header is None:
        header = ["col1", "col2"]
    return header, rows


def convert_one(path: str):
    header, rows = parse_txt_to_rows(path)
    out_path = os.path.splitext(path)[0] + ".csv"

    with open(out_path, "w", newline="", encoding="utf-8-sig") as f:
        w = csv.writer(f, quoting=csv.QUOTE_ALL)
        w.writerow(header)
        w.writerows(rows)

    print(f"已生成: {out_path}  (行数: {len(rows)})")


def main():
    if len(sys.argv) < 2:
        print(
            "用法:将 .txt 文件拖拽到本脚本上,或命令行:python txt2csv_dragdrop.py <file1> [file2...]"
        )
        sys.exit(1)

    for p in sys.argv[1:]:
        # 判断是否是txt文件
        if os.path.isfile(p) and p.lower().endswith(".txt"):
            convert_one(p)
        else:
            print(f"跳过(不是文件): {p}")
    input("处理完成,按回车键退出...")


if __name__ == "__main__":
    main()
posted @ 2025-12-19 09:20  GongYeSUDA  阅读(11)  评论(0)    收藏  举报