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

使用Python ElementTree解析XML导出CSV遇SyntaxError问题求助

解决Python解析XML导出CSV时的SyntaxError: can't assign to literal错误

你遇到的这个语法错误,根源是代码里这行完全写反的赋值操作:

'Test Script (Steps) – Step' = member.find('ns9:description').tag

在Python里,你不能把一个值赋值给字符串字面量——字面量是固定的值,不能作为赋值语句的左操作数,这直接违反了语法规则,所以触发了SyntaxError。

结合你的需求(CSV表头要显示Test Script (Steps) – Step),我给你修正后的完整代码方案,同时补充了一些实用的最佳实践:

#!/usr/bin/python
import xml.etree.ElementTree as ET
import sys, getopt
import csv

def main():
    inputfile = ''
    outputfile = ''
    # 补充命令行参数处理逻辑(你原代码缺失这部分)
    try:
        opts, args = getopt.getopt(sys.argv[1:],"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
        print('test.py -i <input XML file> -o <output CSV file>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -i <input XML file> -o <output CSV file>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    # 必须注册XML命名空间!否则带前缀的标签会无法被定位
    # 替换成你XML文件里实际对应的命名空间URI
    ET.register_namespace('ns2', 'http://your-actual-ns2-namespace-uri')
    ET.register_namespace('ns9', 'http://your-actual-ns9-namespace-uri')

    tree = ET.parse(inputfile)
    root = tree.getroot()

    # 使用with语句自动管理文件,避免资源泄漏
    with open(outputfile, 'w', newline='') as testscript_data:
        csvwriter = csv.writer(testscript_data)
        testscript_head = []
        count = 0

        for member in root.findall('ns2:testscript'):
            testscript = []
            if count == 0:
                # 直接把你想要的表头文本加入列表
                testscript_head.append('Test Script (Steps) – Step')
                # 写入CSV表头
                csvwriter.writerow(testscript_head)
                count += 1
            
            # 获取ns9:description的内容,处理可能的空值情况
            description_elem = member.find('ns9:description')
            step_text = description_elem.text.strip() if (description_elem and description_elem.text) else ''
            testscript.append(step_text)
            
            # 写入该行数据
            csvwriter.writerow(testscript)

if __name__ == "__main__":
    main()

关键修正点说明:

  • 移除错误赋值:直接将目标表头字符串'Test Script (Steps) – Step'添加到表头列表,不需要和XML标签名做无效的赋值操作
  • 命名空间注册:使用带前缀的XML标签(比如ns2:testscript)必须先注册对应的命名空间URI,否则ElementTree无法正确定位元素
  • 文件安全处理:用with语句打开文件,会自动关闭文件,避免手动关闭遗漏导致的资源问题
  • 空值容错:判断description_elem是否存在以及是否有文本内容,防止出现NoneType报错
  • CSV格式优化:添加newline=''参数,避免Windows系统下导出的CSV出现额外空行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:15