使用`print()`写入以二进制模式打开的文件

时间:2019-04-14 19:20:35

标签: python byte

在以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()的使用可能不受支持,但是在那种情况下,错误消息会造成混乱。

1 个答案:

答案 0 :(得分:2)

摘自python3文档:https://docs.python.org/3/library/functions.html#print

  

所有非关键字参数都像str()一样转换为字符串,并写入流中,以sep分隔,然后以end分隔。 sep和end都必须是字符串;它们也可以是None,这意味着要使用默认值。如果未提供任何对象,则print()只会写完。

据我了解,您不能用print() bytes ,因为要写的对象仅在位置参数和位置参数被转换为字符串时才传递(因此错误)。