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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

typeerror write argument must be str not float

Here is an example of how the error occurs.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_float = 3.14 # ⛔️ TypeError: write() argument must be str, not float my_file.write(my_float)
We passed a floating-point number to the write() method, but the method can only be called with a string argument.

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

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

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

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_float = 3.14 my_file.write(str(my_float) + '\n')

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

main.py
my_float = 3.14 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ 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 float" occurs when we try to write a float to a file using the write() method. To solve the error, use the str() class to convert the float 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.