Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: must be str, not float

Tags:

python

string

this is 1/8 of my script:

print('Your skill:', int(charskill))
with open('C:\Documents and Settings\Welcome\My Documents\python\Task 2\lol.txt', 'w') as myFile:
    myFile.write(charskill)

Once I execute on python, it gives me an error of:

Traceback (most recent call last):
  File "C:\Documents and Settings\Welcome\My Documents\python\Task 2\Dice generator v2.py", line 39, in <module>
    myFile.write(charskill)
TypeError: must be str, not float

How do I fix this problem? I want the file to run on notepad ;/ because it is my homework at school.

like image 619
user3024763 Avatar asked Nov 23 '13 13:11

user3024763


People also ask

What does must be str not float mean?

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.

How do you convert a string to a float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.


3 Answers

If you're using Python 3.x (it's possible you might be given your print), then instead of using .write or string formatting, an alternative is to use:

print('Your Skill:', charskill, file=myFile)

This has the advantage of putting a space in there, and a newline character for you and not requiring any explicit conversions.

like image 166
Jon Clements Avatar answered Sep 17 '22 20:09

Jon Clements


You should pass str object to file.write. But it seems like charskill is float object.

Replace following line:

myFile.write(charskill)

with:

myFile.write(str(charskill)) # OR   myFile.write(str(charskill) + '\n')

or

myFile.write('{}'.format(charskill)) # OR  myFile.write('{}\n'.format(charskill))

to convert float to str.

like image 31
falsetru Avatar answered Sep 18 '22 20:09

falsetru


Try casting your float to a string before writing it:

myFile.write(str(charskill))
like image 37
zjm555 Avatar answered Sep 17 '22 20:09

zjm555