首页 > 解决方案 > 如何在python中打开和读取子文件夹中的文件?

问题描述

我创建了一个程序,其中有两个文本文件:“places.txt”和“verbs.txt”,它要求用户在这两个文件之间进行选择。在他们选择之后,它会向用户询问西班牙语单词的英文翻译,并在用户完成“测试”后返回正确答案。但是,如果我在 Mac 上创建的 python 文件夹中的文本文件是免费的,则程序运行顺利,但是一旦我将这些文件和 .py 文件放在子文件夹中,它就会说找不到文件。我想与文本文件一起共享这个 .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

标签: pythonfilesystemsuser-inputlanguage-translation

解决方案


您可能没有从新文件夹中运行脚本,因此它会尝试从您运行脚本的目录中加载文件。尝试设置目录:

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

推荐阅读