Python 代码是一个测验应用程序。尽管文件存在于不同的目录中,但代码返回“filenotfound”错误。
Traceback (most recent call last):
File "/Volumes/HP AKASH/quizePproject/pyquiz/pyquize.py", line 78, in <module>
app = QuizeMain()
^^^^^^^^^^^
File "/Volumes/HP AKASH/quizePproject/pyquiz/pyquize.py", line 8, in __init__
self.qm = QuizeManager(QuizeMain.QUIZE_FOLDER)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Volumes/HP AKASH/quizePproject/pyquiz/quize_management.py", line 24, in __init__
self._build_quiz_list()
File "/Volumes/HP AKASH/quizePproject/pyquiz/quize_management.py", line 27, in _build_quiz_list
dircontent = os.scandir(self.quizefolder)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
NotADirectoryError: [Errno 20] Not a directory: 'pyquiz/quize_xml_files/SampleQuiz.xml'
当我测试
quize_management.py
时,最初它工作正常,但现在它还显示文件未找到错误
akash@AKASHs-MacBook-Air quizePproject % python -u "/Volumes/HP AKASH/quizePproject/pyquiz/quize_management.py"
Traceback (most recent call last):
File "/Volumes/HP AKASH/quizePproject/pyquiz/quize_management.py", line 63, in <module>
qm = QuizeManager("pyquiz/quizers/quizers 16-39-29-621/questions_basics/quize_xml_files")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Volumes/HP AKASH/quizePproject/pyquiz/quize_management.py", line 22, in __init__
raise FileExistsError("The quiz folder does not exist")
FileExistsError: The quiz folder does not exist
我不清楚该错误,因为代码对我来说看起来很好。
Quize_manager 测验管理器类负责管理测验应用程序,它保存数据并保存数据。 init函数中的quizefolder是在pyquize目录quizemain类中初始化的。
import os.path
import os
import datetime
from quiz_perser import QuizePerser
class QuizeManager:
def __init__(self, quizefolder) :
#to store the quizefile
self.quizefolder = quizefolder
#to store the most recent opend quize
self.the_quize = None
#to inisiallize the collection of quizes
self.quizzes = dict()
#to store the result of the most recent quize
self.results = None
#to store the name of the person
self.quizetaker = ""
#to make sure the quizefolder exits
if not os.path.exists(self.quizefolder):
raise FileExistsError("The quiz folder does not exist")
#to build the quize list
self._build_quiz_list()
def _build_quiz_list(self):
dircontent = os.scandir(self.quizefolder)
#to parse the xml file in the quize folder
for i,f in enumerate(dircontent):
if f.is_file():
parser = QuizePerser()
self.quizzes[i+1] = parser.Perser_quize(f)
def list_quizzes(self):
for k, v in self.quizzes.items():
print(f"({k}): {v.name}")
def take_quiz(self, quizid, username):
self.quizetaker = username
self.the_quize = self.quizzes[quizid]
self.results = self.the_quize.take_quiz()
return self.results
def print_results(self):
self.the_quize.print_results(self.quizetaker)
def save_results(self):
n = 0
current_date = datetime.date.today().strftime("%y_%m_%d")
file_name = f"{current_date}.txt"
while(os.path.exists(file_name)):
file_name = f"{current_date}-{n}.txt"
n += 1
with open(file_name, "w") as f:
self.the_quize.print_results(self.quizetaker, f)
if __name__ == "__main__":
qm = QuizeManager("pyquiz/quizers/quizers 16-39-29-621/questions_basics/quize_xml_files")
qm.list_quizzes()
quizemain 类维护测验行为。
from quize_management import QuizeManager
class QuizeMain:
QUIZE_FOLDER = "pyquiz/quize_xml_files/SampleQuiz.xml"
def __init__(self):
self.username = ""
self.qm = QuizeManager(QuizeMain.QUIZE_FOLDER)
def startup(self):
self.greetings()
self.username = input("what is your name: ")
print(f"Welcome : {self.username} ")
def greetings(self):
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~~~~welcome, to the quize~~~~~~~~")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print()
def goodbye(self):
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"Thank you for taking the quiz : {self.username}")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print()
def menu_header(self):
print("Plese seclect a option")
print("M: Repeat this meanu")
print("L: list the quizes")
print("T: Take the Quize")
print("E: exit the program")
print()
def menu_error(self):
print("Your input is invalid, plese try again")
def meanu(self):
self.menu_header()
_response = ""
while (True):
_response = input("enter your choice : ")
_response = _response.capitalize()
if _response[0] == 'E':
self.goodbye()
break
elif _response[0] == 'M':
self.menu_header()
continue
elif _response[0] == 'L':
print("______________________________")
self.qm.list_quizzes()
print("______________________________")
continue
elif _response[0] == 'T':
try:
quiznum = int(input("Enter the number of quize"))
self.qm.take_quiz(quiznum, self.username)
self.qm.print_results()
except:
self.menu_error()
else:
self.menu_error()
def run(self):
self.startup()
self.meanu()
if __name__ == "__main__":
app = QuizeMain()
app.run()
测验目录负责识别多选题型真/假并显示结果和问候语
import datetime
class QuizeApp:
def __init__(self):
self.name = ""
self.description = ""
self.correct_count = 0
self.score = 0
self.total_points = 0
self.questions = []
def take_quiz(self):
self.score = 0
self.correct_count = 0
for q in self.questions:
q.is_correct = False
print("------------------")
for q in self.questions:
q.ask()
if(q.is_correct):
self.score += q.points
self.correct_count += 1
return(self.score,self.correct_count,self.total_points)
def print_results(self, quizetaker):
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"Result for: {quizetaker} ")
print(f"Date: {datetime.datetime.today()}")
print(f"Questions: {self.questions}")
print(f"Correst Questiom: {self.correct_count} out of {len(self.questions)} correctr")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
def greetings(self):
print("`````````````````````")
print("~~~~~~~~~~~~~~~~~~~~~")
print("~~This is a sample questions~~")
print("~~~~~~~~~~~~~~~~~~~~~")
print()
def MenuError(self):
print("You have not ented any choice")
print()
class Questions:
def __init__(self):
self.correct_answer = " "
self.is_correct = False
self.points = 0
self.text =" "
class QuestionsTF(Questions):
def __init__(self):
super().__init__()
def ask(self):
while (True):
print(f"T: True or F: False {self.text} ")
_Answer = input("?")
if len(_Answer) == 0:
print("sorry its not a valid answer ")
continue
_Answer = _Answer.lower()
if (_Answer[0] != "t" and _Answer[0] != "f"):
print ("Invalid Input :")
print(f"T: True or F: False {self.text} ")
continue
if _Answer[0] == self.correct_answer:
self.is_correct = True
break
class QuestionsMulti(Questions):
def __init__(self):
super().__init__()
self.answers = []
def ask(self):
while (True):
print(self.text)
for a in self.answers:
print(f"({a.name} {a.text})")
_Answer = input("?")
if len(_Answer) == 0:
print("sorry its not a valid answer ")
continue
_Answer = _Answer.lower()
if _Answer[0] == self.correct_answer:
self.is_correct = True
break
class Answer:
def __init__(self):
self.text = ""
self.name = ""
QuizParser 类加载特定的测验文件,解析它并返回 一个完整构建的测验对象,然后可以呈现给用户。
import xml.sax
from quize import *
from enum import Enum, unique
# unique function used to find the unique function in an arry or list and return the unique elements only
@unique
class QuizePerserState(Enum):
IDLE = 0
PARSE_QUIZ = 1
PARSE_DESCRIPTION = 2
PARSE_QUESTION = 3
PARSE_QUEST_TEXT = 4
PARSE_ANSWER = 5
class QuizePerser(xml.sax.ContentHandler):
def __init__(self) :
self.new_quize = QuizeApp()
self._perser_state = QuizePerserState.IDLE
self._current_question = None
self._current_answer = None
def Perser_quize(self, quizepath):
quizetext = ""
with open(quizepath, "r", encoding="latin-1") as quizefile: # Or try another encoding like "windows-1252"
if quizefile.mode == "r":
quizetext = quizefile.read()
xml.sax.parseString(quizetext, self)
return self.new_quize
def startElement(self, tagname, attrs ):
if tagname == "QuizML":
self._perser_state = QuizePerserState.PARSE_QUIZ
self.new_quize.name = attrs["name"]
elif tagname == "Description" :
self._perser_state = QuizePerserState.PARSE_DESCRIPTION
elif tagname == "Question":
self._perser_state = QuizePerserState.PARSE_QUESTION
if (attrs["type"] == "multichoice"):
self._current_question = QuestionsMulti()
if (attrs["type"] == "tf"):
self._current_question = QuestionsTF()
self._current_question.points = int(attrs["points"])
self.new_quize.total_points += self._current_question.points
elif tagname == "QuestionText":
self._perser_state = QuizePerserState.PARSE_QUEST_TEXT
self._current_question.correct_answer = attrs["answer"]
elif tagname == "Answer":
self._current_answer = Answer()
self._current_answer.name = attrs["name"]
self._perser_state = QuizePerserState.PARSE_ANSWER
def endElement(self, tagname):
if tagname == "QuizML":
self._perser_state = QuizePerserState.IDLE
elif tagname == "Discription":
self._perser_state = QuizePerserState.PARSE_QUIZ
elif tagname == "Question":
self.new_quize.questions.append(self._current_question)
self._perser_state = QuizePerserState.PARSE_QUIZ
elif tagname =="QuestionText":
self._perser_state = QuizePerserState.PARSE_QUESTION
elif tagname == "Answer":
self._current_question.answers.append(self._current_answer)
self._perser_state = QuizePerserState.PARSE_QUESTION
def characters(self, chars):
if self._perser_state == QuizePerserState.PARSE_DESCRIPTION:
self.new_quize.description += chars
elif self._perser_state == QuizePerserState.PARSE_QUEST_TEXT:
self._current_question.text += chars
elif self._perser_state == QuizePerserState.PARSE_ANSWER:
self._current_answer.text += chars
# if __name__ == '__main__':
# app = QuizePerser()
# qz = app.Perser_quize("pyquiz/quizers/quizers 16-39-29-621/questions_basics/quizers_xml_files/SampleQuiz.xml")
# print(qz.name)
# print(qz.description)
# print(len(qz.questions))
# print(qz.total_points)
# for q in qz.questions:
# print(f"Question: {q.text}")
NotADirectoryError
提示您正在将文件名传递给需要目录名的函数。
QUIZE_FOLDER = "pyquiz/quize_xml_files/SampleQuiz.xml"
看起来很像文件名,而不是目录名。 也许你的意思是
QUIZE_FOLDER = "pyquiz/quize_xml_files"
那里?
顺便说一句,
raise FileExistsError("The quiz folder does not exist")
似乎有点奇怪——这不应该是raise FileNotFoundError(...)
吗?