简体   繁体   中英

Writing to file advice

Here's my code:

import random

ch1=input("Please enter the name of your first character ")
strch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch1+" is:")
print (strch1)
print("and the skill value of "+ch1+" is:")
print (sklch1)

ch2=input("Please enter the name of your second character ")
strch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch2=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch2+" is:")
print (strch2)
print("and the skill value of "+ch2+" is:")
print (sklch2)

myFile = open("CharacterSkillAttributes.txt", "wt")

myFile.write("The attributes of "+ch1+" are: /n")
myFile.write("Strength: "+strch1+"/n")
myFile.write("Skill: "+sklch1+"/n")

myFile.write("The attributes of "+ch2+" are: /n")
myFile.write("Strength: "+strch2+"/n")
myFile.write("Skill: "+sklch2+"/n")

myFile.close()

Here's the error:

Traceback (most recent call last):
  File "E:\Computing Science\Computing science A453\Task 2\task 2 mostly working (needs 'save to file').py", line 22, in <module>
    myFile.write("Strength: "+strch1+"/n")
TypeError: Can't convert 'int' object to str implicitly

I don't want to change the code too much (unless I really have to), just need this problem solved.

Use string formatting to get rid of the error:

file.write('Strength: {0}\n'.format(sklch1))

Obviously you will have to do the same when you write to the file with sklch2 .

You should just make a string from your integer variable:

myFile.write("Strength: " + str(strch1) + "/n")

or as suggested Alex use str.format() .

The error message tells you exactly that, strch1 is an int and you cannot concatenate it with string directly.

You can do

file.write('Strength: %s\n' % (sklch1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM