My code doesn't seem to be able to find a text file I created. The .txt
file is in the same folder as the .py-file
named trivia.txt
. It's from the Python programming for the absolute beginner. I get the following error:
>>>
Unable to open the file trivia.txt Ending program
[Errno 2] No such file or directory: 'trivia.txt'
Traceback (most recent call last):
File "C:\Users\hugok\Desktop\Python programs\Trivia_game.py", line 64, in <module>
main()
File "C:\Users\hugok\Desktop\Python programs\Trivia_game.py", line 39, in main
trivia_file = open_file("trivia.txt", "r")
File "C:\Users\hugok\Desktop\Python programs\Trivia_game.py", line 8, in open_file
sys.exit()
SystemExit
>>>
This is the code I am trying to run:
import sys
def open_file(file_name, mode):
try:
the_file=open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program\n", e)
input=("\nPress the enter key to exit")
sys.exit()
else:
return the_file
def next_line(the_file):
line=the_file.readline()
line=line.replace("/", "\n")
return line
def next_block(the_file):
cathegory=next_line(the_file)
question=next_line(the_file)
answers=[]
for i in range(4):
answers.append(next_line(the_file))
correct=next_line(the_file)
if correct:
correct=correct[0]
explanation=next_line(the_file)
return category, question, answers, correct, explanation
def welcome(title):
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def main():
trivia_file = open_file("trivia.txt", "r")
title=next_line(trivia_file)
welcome(title)
score=0
category, question, answers, correct, explanation=next_block(trivia_file)
while category:
print(category)
print(question)
for i in range(4):
print("\t", i+1, answers[i])
answer=input("What's your answer?")
if answer==correct:
print("\nRight!", end=" ")
score+=1
else:
print("\nWrong!", end=" ")
print(explanation)
category, question, answers, correct, explanation=next_block(trivia_file)
trivia_file.close()
print("That was the last question")
print("Your final score is", score)
main()
input("\n\nPress the enter key to exit.")