1

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.")
kiner_shah
  • 3,939
  • 7
  • 23
  • 37
Hugo Karlsson
  • 11
  • 1
  • 2

2 Answers2

0

Your .txt file being in the same folder as the .py file doesn't really mean anything. You need to make sure that the result of:

import os
os.getcwd()

is the directory where you have your text file. The traceback tells us that it is not. So you have two options here:

  1. Change your working directory at the top of the script to where your text file is:

    os.chdir("C:/Users/hugok/Desktop/Python programs")
    
  2. When you call open(), specify the full path to your text file:

    def main():
        open_file("C:/Users/hugok/Desktop/Python programs/trivia.txt", "r")
        ...
    

Either solution should work, please update us regarding the result once you apply them.

FatihAkici
  • 4,679
  • 2
  • 31
  • 48
  • Thank you. I still get the same error message. I had to change the backslash (\) to regular slash (/) though because of the sama problem described here: https://stackoverflow.com/questions/18084554/why-do-i-get-a-syntaxerror-for-a-unicode-escape-in-my-file-path – Hugo Karlsson Mar 11 '18 at 14:02
  • Oh of course, that change makes sense. Other than that, can you run this and let me know if your text file is in the result: `os.listdir(os.getcwd())` – FatihAkici Mar 11 '18 at 16:06
  • Hi again, sorry for the late reply. But yes the txt-file is in the result of that command: >>> os.listdir(os.getcwd()) ['Hanging_man.py', 'Numberguess.py', 'Numberguess_computer.py', 'pickles.dat', 'read_it.txt', 'skilltree.py', 'test.py', 'trivia.txt.txt', 'Trivia_game.py', 'write_it.txt'] – Hugo Karlsson Mar 24 '18 at 16:24
  • 1
    Well its name is what is confusing you. The name is 'trivia.txt.txt' right now. Go to the folder and rename the file to 'trivia'. That is, delete the .txt part from its name. – FatihAkici Mar 24 '18 at 19:06
  • My point is not so much the user not knowing where the default directory of "file_name.txt" so they can create files in the default directory of the program but how should/can the program designer/builder do to make the program most useful/least confusing. Possibilities include making the file search for non-absolute paths include the directory of the program source among other likely directories. – crs Jul 12 '23 at 16:50
0

A variation on the theme, where the user expects data files to be in the same directory as the program main source code:

# help_user_path.py
import os

"""
    ONLY as a suggestion, let's assume the user,
    unless specifying an absolute file path, expects
    the file to be in the directory of, or relative to the
    program's directory.     
"""
file_name = "test_file.txt"
inp = input(f"Enter File Name[{file_name}]:")
if inp != "":
    file_name = inp     # Use input
file_path = file_name   # Changed, if appropriate
if not os.path.isabs(file_path):
    pgm_dir = os.path.dirname(__file__)
    file_path = os.path.join(pgm_dir,file_name)
    
if not os.path.exists(file_path):
    print(f"Can't find file: {file_name}"
          f"\n at {os.path.abspath(file_path)}")
else:
    print(f"File: {file_name}"
          f"\n at {os.path.abspath(file_path)}"
          f"\n exists")

crs
  • 51
  • 5
  • Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken Jul 11 '23 at 12:49