请记住,我是编程新手。我试图做一个猜数字游戏,并希望将随机数导出到文本文件。我不希望它每次都覆盖这些数字,我只是希望它每次都有一个新的数字,但我不知道如何将数字写入.txt文件。有帮助吗?这是我的代码:
def easy():
print ("")
print ("Difficulty: Easy")
print ("")
irand = randrange(1,10)
with open("GTN.txt", "a") as text_file:
text_file.write(irand + "\n")
while True:
number = input("Pick a number 1 - 10: ")
try:
number = int(number)
except ValueError:
print(" ")
print(number, 'is not a number, try again.')
continue
if number > irand:
print("That's too high, try again.")
print(" ")
time.sleep(1)
elif number < irand:
print("That's too low, try again.")
print(" ")
time.sleep(1)
elif number == irand:
print(" ")
print("You got it right! You won!")
print(" ")
time.sleep(2)
main()
break
提前感谢任何可以帮助我的人。
答案 0 :(得分:2)
您需要将irand
从int
投射到str
,除此之外您的代码还可以:
text_file.write(str(irand) + "\n")