0

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.

1
  • 1
    Try passing strings and use the encoding parameter Commented Apr 14, 2019 at 19:56

1 Answer 1

2

From python3 documentation: https://docs.python.org/3/library/functions.html#print

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

As I understand, you can't write bytes with print() because the object you want to write is passed only as positional argument and positional arguments are converted to strings(hence the error).

Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe I didn't realize this and didn't try to check the docs. Of course it makes sense since you can print() basically anything and get reasonable output. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.