TypeError: must be str, not float

Question:

this is 1/8 of my script:

print('Your skill:', int(charskill))
with open('C:Documents and SettingsWelcomeMy DocumentspythonTask 2lol.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 SettingsWelcomeMy DocumentspythonTask 2Dice 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.

Asked By: user3024763

||

Answers:

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.

Answered By: falsetru

Try casting your float to a string before writing it:

myFile.write(str(charskill))
Answered By: zjm555

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.

Answered By: Jon Clements
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.