将变量值附加到特定文件夹/文件

时间:2015-01-14 08:58:11

标签: python file

我需要将名称和分数附加到程序末尾的特定类文件夹和文件中, print(“你得分”+ str(纠正问题)+“/ 10个问题。”) 学生选择他们所在的课程,在问题结束后,我希望它写入他们的班级文件夹和文本文件,他们是名字和分数。

import random
import time 
import sys

def questions():
    name=input("What is your name: ")
    print("Hello there",name,"!")
    time.sleep(0.5)
    print("What class are you in?")
    time.sleep(0.5)
    print("")#space
    whatClass=input("Enter 1, 2 or 3: ")
    print("")#space
    if whatClass == "1":
        print("You are in class 1!")
    elif whatClass =="2":
        print("You are in class 2!") 
    elif whatClass =="3":
        print("you are in class 3!")
    else: 
        print ("Please try again")
        quit()

    finish = False
    questionnumber = 0
    correctquestions = 0

    while not finish:
        choice = random.choice("+-x")
        if questionnumber < 10 | questionnumber >= 0:
            number1 = random.randrange(1,10)
            number2 = random.randrange(1,10)
            print((number1),(choice),(number2))
            answer=int(input("What is the answer?: "))
            questionnumber = questionnumber + 1

            if choice==("+"):
                realanswer = number1+number2
                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")

            if choice==("x"):
                realanswer = number1*number2
                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")

            elif choice==("-"):
                realanswer = number1-number2

                if answer==realanswer:
                    print("That's the correct answer")
                    correctquestions = correctquestions + 1
                else:
                    print("Wrong answer, the answer was",realanswer,"!")
        else:
            finish = True
    else:
            print("Good job",name,"! You have finished the quiz")
            print("You scored " + str(correctquestions) + "/10 questions.")
            #if the class is 1 append the name and score to folder class1
            #if the class is 2 append the name and score to folder class2
            #if the class is 3 append the name and score to folder class3


questions()

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

import errno

folder= 'class%s'%whatClass
# create the folder if it does not exist
try:
    os.makedirs(folder)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise

# create a file with the student's name in the folder, and write the score
with open(os.path.join(folder, name+'.txt'), 'w') as f:
    f.write(str(score))

另外,请阅读the python docs on file IO

相关问题