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

Python报argument of type 'int' is not iterable错误 邮件附件写入问题

问题根因
  • 方法调用错误:你使用了readline()读取文件,该方法仅返回单行的bytes对象,对bytes对象遍历得到的每个元素是对应单字节的整数,因此做"Error" in i或b"Error" in i判断时,本质是检查字节序列是否存在于整数中,自然会抛出int不可迭代的报错
  • 类型不匹配:使用rb模式读取的文件内容是字节类型,直接和字符串"Error"匹配本身也存在类型兼容问题
修复方案

核心修正两个问题:将读取单行的readline()改为读取所有行的readlines(),统一字节/字符串类型的匹配逻辑,修正后代码如下:

with open(self.filePath, 'rb') as content_file:
    # 读取文件所有行,返回元素为bytes的列表
    content_lines = content_file.readlines()
# 匹配含Error的行,解码为字符串后存入列表,编码可根据你的文件实际格式替换为gbk等
error_lines = [line.decode('utf-8') for line in content_lines if b"Error" in line]
error_content = "\n".join(error_lines)
# 存在错误内容时再添加附件,避免发送空附件
if error_content:
    self.msg.add_attachment(error_content, maintype='text', subtype='plain', filename=self.filePath.split('/')[-1])

如果你的文件是纯文本且编码明确,也可以直接用文本模式打开,省去转码步骤:

# 用文本模式读取,直接返回字符串类型的行内容
with open(self.filePath, 'r', encoding='utf-8') as content_file:
    content_lines = content_file.readlines()
error_lines = [line for line in content_lines if "Error" in line]
error_content = "\n".join(error_lines)
if error_content:
    self.msg.add_attachment(error_content, maintype='text', subtype='plain', filename=self.filePath.split('/')[-1])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:15:03