Python3写入bytes对象仍报‘需bytes-like对象而非str’错误求助
Hey there, I totally get why this is confusing—your debug prints clearly show s is a bytes object, yet the error says you're passing a str! Let's break down what's happening here.
The Root Cause
When you use print(s, file=f) to write to your file, the print() function doesn't just pass the bytes directly to the file. Instead, it automatically converts any object you pass it into a string (using str() under the hood).
So even though s is b'myfancystring', print() turns it into the string "b'myfancystring'" before trying to write it. Since your file is opened in binary mode (wb), it expects raw bytes, not this string representation—and that's exactly why you're seeing the error.
The Fixes
There are two straightforward ways to fix this, depending on your needs:
Use
file.write()instead ofprint()(recommended for binary files)
Thewrite()method of a binary file object accepts bytes directly, no conversion involved. If you want to keep the newline thatprint()adds by default, just appendb'\n'to your bytes:with open(fname, 'wb') as f: for p, values in params: s = p.encode() # Shorter, cleaner way to convert str to bytes print("the type is:", type(s)) print(s) f.write(s + b'\n') # Write raw bytes + newline to match print's default behaviorSwitch to text mode if you don't need binary output
If your goal is to write human-readable text (not raw bytes), open the file withwmode instead ofwb, and you can useprint()normally without converting to bytes first:with open(fname, 'w', encoding='utf-8') as f: for p, values in params: print(p, file=f)
Quick Recap
print()is designed for text output—it converts everything to strings first- Binary files (
wbmode) only accept raw bytes, so usefile.write()for this use case - If you're working with text, use text mode (
w) and skip the bytes conversion entirely
内容的提问来源于stack exchange,提问作者Pfaeff

