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

Python3写入bytes对象仍报‘需bytes-like对象而非str’错误求助

Why You're Getting "a bytes-like object is required, not 'str'" Even With a Bytes Object

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:

  1. Use file.write() instead of print() (recommended for binary files)
    The write() method of a binary file object accepts bytes directly, no conversion involved. If you want to keep the newline that print() adds by default, just append b'\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 behavior
    
  2. Switch 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 with w mode instead of wb, and you can use print() 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 (wb mode) only accept raw bytes, so use file.write() for this use case
  • If you're working with text, use text mode (w) and skip the bytes conversion entirely

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:43:09