我正在尝试将数据写入python中的文本文件,我试图让用户选择文件名作为字符串。但是,当涉及到实际写入数据时,它会显示错误。
import random
name = input("Please enter your name: ")
clas = input("Please enter what class you are in: ")
#Uses a list to show the 3 operators I want to use
ops = ['+', '-', '*']
#Defines two variables as 1 and 0
x = 1
score = 0
#While the variable x is less than or equal to 10, the loop will continue
while x <= 10:
#Selects 2 random integers from 1 to 10
num1 = random.randint(1,10)
num2 = random.randint(1,10)
#Choses the operation from the list `ops`
operation = random.choice(ops)
#Prints the 2 numbers and operation in an arithmetic question layout
print(num1,operation,num2)
maths = int(eval(str(num1) + operation + str(num2)))
#Gets the user to input there answer to the question
answer = int(input("What is the answer to that arithmetic question? "))
#If the answer the user input is equal to the correct answer the user scores a point and is told it is correct
#Otherwise, the answer must be wrong so the user is told his score is incorrect and that no points are scored
if answer == maths:
print ("Correct")
score += 1
else:
print ("Incorrect Answer")
#Add one onto the score that the while loops depends on to make sure it only loops 10 times
x = x + 1
#Leaves the iteration after 10 loops and prints the users final score
print ("You scored", score, " out of 10 points")
score2 = str(score)
score = str(name + score2 + "\n")
with open(clas."txt", "a") as scorefile:
scorefile.write(score)
答案 0 :(得分:1)
要写入文件:
f = open("filename.txt","w")
f.write("Writing to a file!")
# writes "Writing to a file!" as a new line in filename.txt
f.close()
阅读文件:
f = open("filename.txt","r")
lines = f.readlines()
f.close()
print lines
# prints array
确保使用f.close(),否则会发生不好的事情。