TypeError: write() argument must be str, not bytes

Recently I encountered this error: "TypeError: write() argument must be str, not bytes" when trying to write a PDF file from anaconda 3. The solution was to write stream in binary.


Error:

J:\>python pdf.py
Traceback (most recent call last):
  File "pdf.py", line 31, in <module>
    fd.write(buf.getvalue())
TypeError: write() argument must be str, not bytes

Problem code:

# Write the PDF to a file
with open('test.pdf', 'w') as fd:
    fd.write(buf.getvalue())

Solution:

# Write the PDF to a file
with open('test.pdf', 'wb') as fd:
    fd.write(buf.getvalue())

This Python error happens when binary data is written to a file opened in text mode, which is common when producing a PDF or other binary output.

Opening the file in binary mode, for example with the wb flag, lets you write bytes directly and resolves it. Writing text to a file opened in binary mode raises the opposite error.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram