Python写入文件报错TypeError:需bytes类对象而非str,求解决
解决Python文件写入的TypeError问题
嘿,别慌!作为编程新手遇到这种问题太正常了,我来一步步帮你弄明白为啥报错,以及怎么修复~
错误原因拆解
你遇到的TypeError: a bytes-like object is required, not 'str',根源出在这行代码:
file = open(fileName, "wb")
"wb"是二进制写入模式,这种模式下,Python要求你写入的内容必须是bytes类型(字节对象),但你准备的outputString是普通的字符串(str类型),类型不匹配就触发了错误。
另外,你的代码里还有两个小语法问题,不修复的话也会报错:
- 第二行
input("whats ure email:)的双引号没闭合,应该改成input("whats ure email: ") - 第五行
outputString = name + "|" email + "|" + favoriteband里,"|"和email之间少了一个+号,应该是name + "|" + email + "|" + favoriteband
两种修复方案
方案1:用文本模式打开文件(推荐)
把打开文件的模式从"wb"改成"w"(文本写入模式),这样就能直接写入字符串了。如果担心字符编码问题,最好加上encoding="utf-8"参数,避免中文等特殊字符乱码:
修复后的完整代码:
name = input("name: ") email = input("what's your email: ") favoriteband = input("your fav band: ") outputString = name + "|" + email + "|" + favoriteband fileName = name + ".txt" # 用文本模式打开,指定编码 file = open(fileName, "w", encoding="utf-8") file.write(outputString) print(outputString , " saved in ", fileName) file.close()
方案2:将字符串转为字节对象(保留二进制模式)
如果你非要用二进制模式(比如某些特殊场景需要),可以把字符串通过encode()方法转成bytes类型,再写入文件:
name = input("name: ") email = input("what's your email: ") favoriteband = input("your fav band: ") outputString = name + "|" + email + "|" + favoriteband fileName = name + ".txt" file = open(fileName, "wb") # 将字符串转为utf-8编码的字节对象 file.write(outputString.encode("utf-8")) print(outputString , " saved in ", fileName) file.close()
额外小建议
以后打开文件的时候,推荐用with语句,它会自动帮你关闭文件,不用手动调用file.close(),更安全也更简洁:
name = input("name: ") email = input("what's your email: ") favoriteband = input("your fav band: ") outputString = name + "|" + email + "|" + favoriteband fileName = name + ".txt" with open(fileName, "w", encoding="utf-8") as file: file.write(outputString) print(outputString , " saved in ", fileName)
内容的提问来源于stack exchange,提问作者pio
相关产品推荐
相关产品推荐

