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

Python处理XML写入文件报错:参数需为str而非bytes

移除XML中金额为0.00的条目时遇到TypeError问题

我有大约10万条XML格式的price-table记录,需要移除金额为0.00的条目,数据结构如下:

<data>
    <price-table product-id="100109a">
        <amount quantity="1">10.00</amount>
    </price-table>
    <price-table product-id="201208c">
        <amount quantity="1">0.00</amount>
    </price-table>
</data>

我尝试用Python完成该工作,代码如下:

from xml.etree import ElementTree as ET

def readfile():
    with open('prices.xml') as f:
        contents = f.read()
        return(contents)

xml_string = readfile()

root = ET.fromstring(xml_string)

for price_table in root.findall('price-table'):
    amount = price_table.find('amount')
    if float(amount.text) != 0:
        root.remove(price_table)

xmltowrite = ET.tostring(root)
#print(xmltowrite)

with open('xmlwrite.txt', 'w') as j:
    j.write(xmltowrite) 

运行代码时出现错误:

TypeError: write() argument must be str, not bytes

但我认为ET.tostring()函数应该会将xmltowrite转换为字符串,为什么最终它不是字符串呢?


问题原因与解决方案

1. 字节/字符串类型问题的原因

在Python 3中,ET.tostring()默认返回字节对象(bytes),而非字符串(str)。该函数默认以UTF-8编码输出字节流,而你用文本模式('w')打开文件时,要求写入的必须是字符串,因此触发TypeError。

2. 解决类型错误的两种方法

  • 方法一:让ET.tostring()直接返回字符串
    调用时指定encoding='unicode'参数:
    xmltowrite = ET.tostring(root, encoding='unicode')
    
  • 方法二:将字节对象解码为字符串
    对返回的字节流进行UTF-8解码:
    xmltowrite = ET.tostring(root).decode('utf-8')
    

3. 修正逻辑错误

你的代码当前是移除金额不为0的条目,和需求完全相反!需要把判断条件改成:

if float(amount.text.strip()) == 0.00:
    root.remove(price_table)

加上.strip()是为了避免金额文本中存在空格等空白字符导致转换错误。

4. 针对10万条记录的优化建议

直接使用ET.parse()解析文件,而非先把整个文件读成字符串,这样能降低内存占用,更适合处理大文件:

from xml.etree import ElementTree as ET

# 直接解析文件,无需加载全部内容到内存
tree = ET.parse('prices.xml')
root = tree.getroot()

# 遍历并移除金额为0的条目
for price_table in root.findall('price-table'):
    amount = price_table.find('amount')
    if float(amount.text.strip()) == 0.00:
        root.remove(price_table)

# 直接用tree.write写入文件,自动处理编码问题
tree.write('xmlwrite.txt', encoding='utf-8', xml_declaration=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:05:19