How to Resolve Python "TypeError: write() argument must be str, not ..."
The TypeError: write() argument must be str, not X (where X could be bytes, list, dict, tuple, None, etc.) is a common error when working with file I/O in Python. It occurs because the file.write() method, when a file is opened in text mode ('w', 'a', 'r+'), expects a string argument, but receives an object of a different, incompatible type.
This guide explains why this error happens and provides solutions for various types.
Understanding the Error: Text Mode vs. Binary Mode
Python's open() function has different modes:
- Text Mode (e.g.,
'w','r','a','r+'): Used for reading and writing text (strobjects). Data is automatically encoded/decoded using a specified (or default) encoding.write()expects astr. - Binary Mode (e.g.,
'wb','rb','ab','rb+'): Used for reading and writing raw binary data (bytesobjects). No encoding/decoding happens.write()expects abytes-like object.
The TypeError occurs when you open a file in text mode but try to write() something that isn't a string.