如何使用 Python 写入文件?

Jos*_*iff 5 python file-io

我如何将分数写入文件?

import random
score=0
question=0
for i in range(10):
       num1= random.randint(1,10)
       num2= random.randint(1,10)
       ops = ['+', '-', '*']
       operation = random.choice(ops)
       Q = int(input(str(num1)+operation+str(num2)))

       if operation =='+':
              answer=num1+num2
              if Q == answer:
                     print ("correct")
                     score=score+1

              else:
                     print('You Fail')

       elif operation =='-':
              answer=num1-num2
              if Q == answer:
                     print ("correct")
                     score=score+1
              else:
                     print("you fail")

       else:
              answer=num1*num2
              if Q == answer:
                     print ("correct")
                     score=score+1
              else:
                     print("you fail")
print("thank you for playing your score is",score)
Run Code Online (Sandbox Code Playgroud)

Sir*_*lot 4

您可以手动打开和关闭文件,但最好使用它,with因为它会为您处理关闭文件。

with open("score_file.txt",'a') as f:
    f.write(score)
Run Code Online (Sandbox Code Playgroud)

'a'意味着追加到不会覆盖以前内容的文件 - 这就是您可能正在寻找的内容。据我所知,您需要在 print 语句之后或之前添加它。如果您不了解文件的读取和写入,那么您应该查看此链接