如何使用Python写入文件? [英] How to write to file with Python?

查看:88
本文介绍了如何使用Python写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将分数写入文件?

How would I write the scores to a file?

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)

推荐答案

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

You can manually open and close a file but it is better to use with since it handles closing the file for you.

with open("score_file.txt",'a') as f:
    f.write(score)

'a'表示追加到文件中,该文件不会覆盖以前的内容-这可能是您要查找的内容.据我所知,您将要在print语句之后或之前添加它.如果您不懂读写文件,则应该查看此链接.

'a' means append to file which does not overwrite the previous contents - this is what you are probably looking for. From what I can tell you are going to want to add this after the print statement or right before. If you don't understand reading and writing to files, then you should check out this link.

这篇关于如何使用Python写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆