将变量附加到不在Python中工作的文本文件

时间:2015-10-12 11:37:51

标签: python python-3.x

我试图让我的程序在完成运行之后将两个变量输出到文本文件,但我得到的只是文件夹,里面没有文本文件。以下是有问题的代码:

我已编辑过包含整个程序。

import random #needed for the random question creation
import os #needed for when the scores will be appended to a text file
#import csv #work in progress
answer = 0 #just to ensure a strage error isn't created by the input validation (since converting to a global variable isn't really needed)
global questionnumber #sets the question number to be a global variable so that 
questionnumber = 0
global score
score = 0
global name
name = "a"
def check_input(user_input): #used to verify that input by user is a valid number
    try: #the condition that does the checking
        answer = int (user_input)
    except ValueError: #what to do if the number isn't actually a number
        return fail() #calls the failure message
    return answer #sends the answer back to the rest of the program
def fail(): #the failure message procedure defined
   print("That isn't a whole number! Try again with a different question") #tells the user what's going on
   global questionnumber #calls the global variable for this procedure
   questionnumber = questionnumber - 1 #allows the user, who made a mistake, a second chance to get it right
def questions(): #the question procedure defined
    global name
    name=input("Enter your name: ") #gets the user's name for logging and also outputting messages to them
    print("Hello there",name,"! Please answer 10 random maths questions for this test!") #outputs welcome message to the user
    ClassOfStudent=input("Which class are you in?") #gets the user's class for logging
    finish = False
    while finish == False: #only occurs if "finish" isn't set to true so that the questions asked don't exceed ten
        global questionnumber #calls the global variable
        global score
        choice = random.choice("+-x") #uses the random function to choose the operator
        if questionnumber < 10 | questionnumber >= 0: #validation to ensure the question number is within ten
            number1 = random.randrange(1,12) #uses random numbers from the random function, above 1 and below 12
            number2 = random.randrange(1,12) #same as the abovem for the second number
            print((number1),(choice),(number2)) #outputs the sum for the student to answer
            answer=check_input((input("What is the answer?"))) #asks for the student's answer
            questionnumber = questionnumber + 1 #adds one to the numebvr of questions asked

            if choice==("+"): #if the ramdomly generated operator was plus
                correctanswer = number1+number2 #operator is used with the numbers to work out the right answer
                if answer==correctanswer: #checks the studen't answer is right
                    print("That's the correct answer") #if it is, it tells the student
                    score = score + 1 #adds one to the score that the user has
                else:
                    print("Wrong answer, the answer was",correctanswer,"!") #if the answer is wrong, it tells the student and doesn't add one to the score

            if choice==("x"): #essentially the same as the addition, but with a multiplicatin operator instead
                correctanswer = number1*number2
                if answer==correctanswer:
                    print("That's the correct answer")
                    score = score + 1
                else:
                    print("Wrong answer, the answer was",correctanswer,"!")

            elif choice==("-"): #essentially the same as the addition, but with a subtraction operator instead
                correctanswer = number1-number2

                if answer==correctanswer:
                    print("That's the correct answer")
                    score = score + 1
                else:
                    print("Wrong answer, the answer was",correctanswer,"!")
        else: #if the number of questions asked is ten, it goes on to end the program
            finish = True
    else:
            print("Good job",name,"! You have finished the quiz") #outputs a message to the user to tell them that they've finished the quiz
            print("You scored " + str(score) + "/10 questions.") #ouputs the user's score to let them know how well they've done
            #all below here is a work in progress
            #Create a new directory for the scores to go in, if it is not there already.
            if os.path.exists("Scores") == False:
              os.mkdir("Scores")
            os.chdir("Scores")
            if ClassOfStudent==1: #write scores to class 1 text
                file_var = open("Class 1.txt",'w+')
                file_var.write("name, score")
                file_var.close()
            if ClassOfStudent==2: #write score to class 2 text
                file_var = open("Class 2.txt",'w+')
                file_var.write(name, score)
                file_var.close()
            if ClassOfStudent==3: #write score to class 3 text
                file_var = open("Class 3.txt",'w+')
                file_var.write(name, score)
                file_var.close()
questions()

3 个答案:

答案 0 :(得分:1)

ClassOfStudent是一个字符串而不是一个数字,因此写入该文件的代码都不会被执行。您可以通过在每个print下添加if语句来轻松验证,以便查看该代码是否正在执行。

解决方案是与字符串进行比较,或将ClassOfStudent转换为i teger。

答案 1 :(得分:0)

首先你遇到问题“”。你必须更正以下内容:

if ClassOfStudent==2: #write scores to class 1 text
            file_var = open("Class 2.txt",'w+')
            file_var.write("name, score")
            file_var.close()
if ClassOfStudent==3: #write scores to class 1 text
            file_var = open("Class 3.txt",'w+')
            file_var.write("name, score")
            file_var.close()

注意我在写中添加了“”。 无论如何,我认为你想要的是: file_var.write(“name%s,得分%s”%(名称,得分))。这应该更合适。

答案 2 :(得分:0)

使用print(repr(ClassOfStudent))显示值并输入:

>>> ClassOfStudent = input("Which class are you in?")
Which class are you in?2
>>> print(repr(ClassOfStudent))
'2'

在Python 3中使用input()将以字符串形式读取值。您需要将其转换为int或对字符串进行比较。

ClassOfStudent = int(input("Which class are you in?")

应该解决你的问题。