Python找不到.txt文件

时间:2018-03-11 07:16:00

标签: python python-3.x

我的代码似乎无法找到我创建的文本文件。 .py-file文件与名为trivia.txt的{​​{1}}位于同一文件夹中。这是绝对初学者的Python编程。我收到以下错误:

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

这是我试图运行的代码:

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.")

1 个答案:

答案 0 :(得分:0)

您的.txt文件与.py文件位于同一文件夹中并不意味着什么。您需要确保结果:

import os
os.getcwd()

是您拥有文本文件的目录。追溯告诉我们事实并非如此。所以你有两个选择:

  1. 将脚本顶部的工作目录更改为文本文件所在的位置:

    os.chdir("C:/Users/hugok/Desktop/Python programs")
    
  2. 致电open()时,请指定文字文件的完整路径:

    def main():
        open_file("C:/Users/hugok/Desktop/Python programs/trivia.txt", "r")
        ...
    
  3. 任何一种解决方案都应该有效,请在应用后将结果更新给我们。