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

