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

Python2.7中f.write写入报错:TypeError: cannot concatenate 'str' and 'int' objects

错误原因

你代码里的data是整数类型,Python2.7不允许直接把整数和字符串用+运算符拼接,而f.write()方法要求传入字符串参数,所以触发了TypeError: cannot concatenate 'str' and 'int' objects错误。

解决方法
  • 方法1:将整数转为字符串
    直接用str()函数把data转成字符串后再写入:
data = 3673256654

print(data)

f = open("save.txt", 'a') 
f.write(str(data) + "\n")  # 把data转为字符串
f.close()
  • 方法2:使用字符串格式化(更灵活)
    用Python的格式化语法,把整数嵌入字符串中:
    旧式格式化写法:

    f.write("%d\n" % data)
    

    str.format()方法写法:

    f.write("{}\n".format(data))
    
  • 方法3:用with语句管理文件(推荐)
    with语句会自动帮你关闭文件,避免手动关闭可能出现的遗漏问题:

data = 3673256654
print(data)

with open("save.txt", 'a') as f:
    f.write(str(data) + "\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:35:33