String 蟒蛇3-“;需要类似字节的对象,而不是';str'&引用;论类型对象<;类别';字节'&燃气轮机;

String 蟒蛇3-“;需要类似字节的对象,而不是';str'&引用;论类型对象<;类别';字节'&燃气轮机;,string,python-3.x,io,String,Python 3.x,Io,以下代码导致我出现问题: with open(fname, 'wb') as f: for p, values in params: s = str.encode("%s" % p) print("the type is:", type(s)) print(s) print(s, file=f) 输出为: the type is: <class 'bytes'> b'myfancystring' ... Typ

以下代码导致我出现问题:

with open(fname, 'wb') as f:
    for p, values in params:
        s = str.encode("%s" % p)
        print("the type is:", type(s))
        print(s)
        print(s, file=f)
输出为:

the type is: <class 'bytes'>
b'myfancystring'
...
TypeError: a bytes-like object is required, not 'str'
类型为:
b'myfancystring'
...
TypeError:需要类似字节的对象,而不是“str”
所以它是一个“bytes”类型的对象,并且仍然给我这个错误?我很困惑

多谢各位

您好,
Pfaeff

print始终将其输入格式化为字符串,然后再将其传递给文件对象的write()方法,无论该文件对象是stdout(默认值)还是您指定的。这就是为什么print(3)不会给您一个错误,如“string expected but get int”,而就这一点而言,将该字节字符串打印到控制台不会给您一个错误,如“string expected but get bytes”

直接使用文件对象的write()方法:

f.write(b)

它能与“print(bytes,file=f)”一起工作吗?同样的错误:print(bytes,file=f)TypeError:需要一个类似字节的对象,而不是“str”。我认为print不适合写入二进制数据。f、 write()似乎可以完成这项工作。我怀疑prints在内部转换为str,然后将结果传递给f.write(),这将产生错误。