TypeError: write() argument must be str, not int (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: write() argument must be str, not int (Python) #

The Python "TypeError: write() argument must be str, not int" occurs when we try to write an integer to a file using the write() method. To solve the error, use the str() class to convert the integer to a string before writing it to the file.

typeerror write argument must be str not int

Here is an example of how the error occurs.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_int = 100 # ⛔️ TypeError: write() argument must be str, not int my_file.write(my_int)
We passed an integer to the write() method, but the method can only be called with a string argument.

To solve the error, convert the integer to a string before writing it to the file.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_int = 100 my_file.write(str(my_int) + '\n')

The \n string adds a newline character at the end of the line, you can remove it if you don't need it.

If you want to append rather than override the contents of the file, use the a mode instead of w.

main.py
with open('example.txt', 'a', encoding='utf-8') as my_file: my_int = 100 my_file.write(str(my_int) + '\n')

The str() class converts the passed in object to a string.

If you aren't sure what type of object a variable stores, use the type() class.

main.py
my_int = 100 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: write() argument must be str, not int" occurs when we try to write an integer to a file using the write() method. To solve the error, use the str() class to convert the integer to a string before writing it to the file.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.