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.
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.
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.
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.
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
.
Try casting your float to a string before writing it:
myFile.write(str(charskill))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With