简体   繁体   English

将变量附加到文本文件在 Python 中不起作用

[英]Appending variable to text file not working in Python

I am trying to get my program to output two variables to a text file after it finishes running something but all I get is the folder and no text files inside of it.我试图让我的程序在完成运行后将两个变量输出到一个文本文件,但我得到的只是文件夹,里面没有文本文件。 Here is the code in question:这是有问题的代码:

I have edited to include the entire program.我已编辑以包含整个程序。

 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()

ClassOfStudent is a string rather than a number, so none of the code that writes to the file will get executed. ClassOfStudent是一个字符串而不是一个数字,因此写入文件的任何代码都不会被执行。 You can easily verify that by adding a print statement under each if so you can see if that code is being executed.您可以通过在每个if下添加print语句来轻松验证这一点,以便您可以查看该代码是否正在执行。

The solution is to compare to strings, or convert ClassOfStudent to an i teger.解决方案是与字符串进行比较,或将ClassOfStudent转换为 i teger。

first you have a problem with the "".首先你有“”的问题。 you have to correct the following:您必须更正以下内容:

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()

notice that I added the "" inside the write.请注意,我在写入中添加了“”。 In any case, I think what you want is something like: file_var.write("name %s, score %s"%(name,score)).无论如何,我认为你想要的是:file_var.write("name %s, score %s"%(name,score))。 This should be more appropriate.这个应该比较合适。

Use print(repr(ClassOfStudent)) to show the value and type:使用print(repr(ClassOfStudent))显示值和类型:

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

Using input() in Python 3 will read the value in as a string.在 Python 3 中使用input()会将值作为字符串读取。 You need to either convert it to an int or do the comparison against a string.您需要将其转换为int或与字符串进行比较。

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

should fix your problem.应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM