Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open and read a file in python while it's an subfolder?

I have created a program where I have two text files: "places.txt" and "verbs.txt" and It asks the user to choose between these two files. After they've chosen it quizzes the user on the English translation from the Spanish word and returns the correct answer once the user has completed their "test". However the program runs smoothly if the text files are free in the folder for python I have created on my Mac but once I put these files and the .py file in a subfolder it says files can't be found. I want to share this .py file along with the text files but would there be a way I can fix this error?

def CreateQuiz(i):
    # here i'm creating the keys and values of the "flashcards"
    f = open(fileList[i],'r') # using the read function for both files
    EngSpanVocab= {} # this converts the lists in the text files to dictionaries
    for line in f:
        #here this trims the empty lines in the text files
        line = line.strip().split(':')
        engWord = line[0]
        spanWord = line[1].split(',')
        EngSpanVocab[engWord] = spanWord
    placeList = list(EngSpanVocab.keys())
    while True:
        num = input('How many words in your quiz? ==>')
        try:
            num = int(num)
            if num <= 0 or num >= 10:
                print('Number must be greater than zero and less than or equal to 10')
            else:
                correct = 0
                #this takes the user input
                for j in range(num):
                    val = random.choice(placeList)
                    spa = input('Enter a valid spanish phrase for '+val+'\n'+'==> ')
                    if spa in EngSpanVocab[val]:
                        correct = correct+1
                        if len(EngSpanVocab[val]) == 1:
                            #if answers are correct the program returns value
                            print('Correct. Good work\n')
                        else:
                            data = EngSpanVocab[val].copy()
                            data.remove(spa)
                            print('Correct. You could also have chosen',*data,'\n')
                    else:
                        print('Incorrect, right answer was',*EngSpanVocab[val])
                #gives back the user answer as a percentage right out of a 100%
                prob = round((correct/num)*100,2)
                print('\nYou got '+str(correct)+' out of '+str(num)+', which is '+str(prob)+'%'+'\n')
                break

        except:
            print('You must enter an integer')

def write(wrongDict, targetFile):
    # Open
    writeFile = open(targetFile, 'w')
    # Write entry
    for key in wrongDict.keys():
    ## Key
        writeFile.write(key)
        writeFile.write(':')
    ## Value(s)
        for value in wrongDict[key]:
            # If key has multiple values  or user chooses more than 1 word to be quizzed on 
            if value == wrongDict[key][(len(wrongDict[key])) - 1]:
                writeFile.write(value)
            else:
                writeFile.write('%s,'%value)
        writeFile.write('\n')
    # Close
    writeFile.close()
    print ('Incorrect answers written to',targetFile,'.')

def writewrong(wringDict):
    #this is for the file that will be written in 
    string_1= input("Filename (defaults to \'wrong.txt\'):")
    if string_1== ' ':
        target_file='wrong.txt'
    else:
        target_file= string_1
    # this checs if it already exists and if it does then it overwrites what was on it previously
    if os.path.isfile(target)==True:
        while True:
            string_2=input("File already exists. Overwrite? (Yes or No):")
            if string_2== ' ':
                write(wrongDict, target_file)
                break
            else:
                over_list=[]
                for i in string_1:
                     if i.isalpha(): ovrList.append(i)
                ovr = ''.join(ovrList)
                ovr = ovr.lower()
                if ovr.isalpha() == True:
    #### Evaluate answer
                    if ovr[0] == 'y':
                        write(wrongDict, target)
                        break       
                    elif ovr[0] == 'n':
                        break
                else:
                    print ('Invalid input.\n')
    ### If not, create
    else:
        write(wrongDict, target)

def MainMenu():
##    # this is just the standad menu when you first run the program 
    if len(fileList) == 0:
        print('Error! No file found')
    else:
        print( "Vocabulary Program:\nChoose a file with the proper number or press Q to quit" )
        print(str(1) ,"Places.txt")
        print(str(2) ,"Verbs.txt")
while True:
    #this takes the user input given and opens up the right text file depending on what the user wants 
    MainMenu()
    userChoice = input('==> ')
    if userChoice == '1':
        data = open("places.txt",'r')
        CreateQuiz(0)
    elif userChoice == '2':
        data = open("verbs.txt",'r')
        CreateQuiz(1)
    elif userChoice == 'Q':
        break
    else:
        print('Choose a Valid Option!!\n')
    break
like image 243
Jake Avatar asked Dec 31 '25 11:12

Jake


1 Answers

You are probably not running the script from within the new folder, so it tries to load the files from the directory from where you run the script. Try setting the directory:

import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')
like image 73
RJ Adriaansen Avatar answered Jan 03 '26 02:01

RJ Adriaansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!