使用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
相关产品推荐
相关产品推荐

