I often use print() instead of file.write() when writing to files in Python. Recently, I had to write out some binary data, and tried a similar pattern:
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()
My first thought was the default newline-appending behaivor of print() might be at fault:
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
Unfortunately, none of the permutations of changing the end worked.
Why is this happening? I suspect that this use of print() might not be supported, but in that case the error message is quite confusing.