2015-10-27 213 views
-1

我正嘗試將數據寫入到python中的文本文件,並試圖讓用戶選擇文件的名稱作爲字符串。但是,實際編寫數據時,會顯示錯誤。將數據寫入.txt文件

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)  
+2

請將錯誤與您的代碼一起發佈 – Darendal

+0

語法無效,第34行 –

+0

您需要在scorefile.write(分數)一行再加上一個標籤 – Darendal

回答

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(),否則不好的事情會發生