如何在Python中打开和读取子文件夹中的文件?

3
我创建了一个程序,其中有两个文本文件:“places.txt”和“verbs.txt”,它会要求用户在这两个文件中进行选择。一旦用户选择了文件,它就会对英语翻译进行测试,并在用户完成他们的“测试”后返回正确答案。但是,如果将这些文件和.py文件放在子文件夹中,程序会提示找不到文件,只有当这些文件在我Mac上为Python创建的文件夹中时,程序才能正常运行。我想与文本文件一起分享这个.py文件,但是否有办法解决此错误?
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
1个回答

1

你可能没有在新文件夹中运行脚本,所以它试图从你运行脚本的目录加载文件。 尝试设置目录:

import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')

1
我刚刚尝试按照这个建议运行,但它立即输出了"错误!找不到文件"。 - undefined
好的,由于无法确定您从哪里运行该文件,我已经更新了答案,所以无论在什么情况下都应该能够加载该文件 - 只要txt文件与您尝试运行的python文件位于同一目录中。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接