如何使用Python写入文件?

问题描述 投票:2回答:3

我如何将分数写入文件?

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)
python file-io
3个回答
0
投票

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

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

'a'表示追加到文件中,该文件不会覆盖以前的内容-这可能是您想要的。据我所知,您将要在print语句之后或之前添加它。如果您不懂读写文件,则应签出this link


1
投票

这是打开和写入文件的方式:

# Open a file
fo = open("foo.txt", "w") # Creates a file object 'fo'
fo.write("Output text goes here")

# Close opened file (good practice)
fo.close()

0
投票

这里是打开和写入文件的代码示例。

import random

score = 0
question = 0
output = open('my_score', 'a')
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 += 1

       else:
           print('You Fail')

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

print("thank you for playing your score is", score)
output.write(score)
output.close()
© www.soinside.com 2019 - 2024. All rights reserved.