在 Python 中写入文件时,我经常使用print()而不是。file.write()最近,我不得不写出一些二进制数据,并尝试了类似的模式:
f = open('test.txt', 'w')
f.write('abcd')
print('efgh', file=f)
f.close()
f = open('test.bin', 'wb')
f.write(b'abcd') # works as expected
print(b'efgh', file=f)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: a bytes-like object is required, not 'str'
f.close()
我的第一个想法是默认的换行附加行为print()可能有问题:
print(b'efgh', file=f, end='')
# same error
print(b'efgh', file=f, end=None)
# same error
print(b'efgh', file=f, end=b'')
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: end must be None or a string, not bytes
print(b'efgh', file=f, end=b'\n')
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: end must be None or a string, not bytes
不幸的是,改变结尾的排列都没有奏效。
为什么会这样?我怀疑print()可能不支持这种使用,但在这种情况下,错误消息非常令人困惑。