0

在 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()可能不支持这种使用,但在这种情况下,错误消息非常令人困惑。

4

1 回答 1

2

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

所有非关键字参数都像 str() 一样转换为字符串并写入流,由 sep 分隔,后跟 end。sep 和 end 都必须是字符串;它们也可以是 None,这意味着使用默认值。如果没有给出对象, print() 将只写 end。

据我了解,您不能写入字节print()因为您要写入的对象仅作为位置参数传递,并且位置参数被转换为字符串(因此出现错误)。

于 2019-04-14T19:45:46.683 回答