基本上我有一个代码,输入2个强度和技能的随机数。这两个输入我想保存在记事本中。该数字为力量和技能生成一个随机数,我希望每次都能将数字保存在记事本中。因此,当我回头看记事本时,它显示了生成的最后一个数字。到目前为止,这是我的代码:
import random
playname1 = str(input("Enter player one name"))
print("Welcome",playname1)
strength1 = random.randint(1,12)
strength2 = random.randint(1,4)
strength3 = (strength1/strength2)
strength4 = round(strength3)
strength5= (10+strength4)
print ("Your strength is...",strength5)
skill1 = random.randint(1,12)
skill2 = random.randint(1,4)
skill3 = (skill1/skill2)
skill4 = round(skill3)
skill5= (10+skill4)
print ("Your skill is...",skill5)
代码的下一部分我想成为保存在记事本上的力量和技能的两个数字。
答案 0 :(得分:0)
最简单的方法是
import os
strength5,skill5 =10,20
with open("data.txt") as f:
f.write("%s %s"%(strength5, skill5))
os.startfile("data.txt")
假设我明白你的意思是“保存在记事本上”(例如,你不是说把它写在便利贴上?)
答案 1 :(得分:0)
您没有指定正在使用的Python版本,但根据您的语法,我假设您使用的是Python3?首先,你不需要做str(input(...))
- 那已经是一个str。
在Python3中,写入文件的正确方法是:
with open('text.txt', 'w') as f:
print('a sentence', file=f) // this will add a new line at the end automatically
// or you can do:
// f.write('a sentence\n')
// since write doesn't add new line automatically, you need to explicitly type \n
答案 2 :(得分:0)
在初始化中打开文件。
f = open('output.txt', 'w')
请注意,这会在写入模式下打开,因此以前的所有数据都将被删除。如果你想附加使用
f = opr('output.txt', 'a')
现在只需编写文本数据
datatxt = ' '.join(str(strength5), str(skill5))
f.write(datatxt)
完成后
f.close()