首页 > 解决方案 > 该文件位于文件夹内,但我遇到 WinError 3 找不到文件

问题描述

我正在尝试学习 python,并且我已经为随机 madlib 生成器编写了此代码。但是当我去运行程序时,它说它找不到指定的路径,尽管文件夹存在并且保存了 .json 文件。我在 Windows 10 上。为什么会出现此错误?是因为 ./ 是 Linux 命令吗?感谢您的帮助和建议。

我在这里发布我的代码:

import random
import json
import os


class CreateaMadLib:
    Path = "./MadLibGen"
    def __init__(self, Word_Desc, Temp):
        self.Temp = Temp
        self.Word_Desc = Word_Desc
        self.UserInput = []
        self.Story = None
        
        
    @classmethod
    def Get__From__Json(cls, Name, Path=None):
        if not Path:
            Path = cls.path
        fpath = os.path.join(Path, Name)
        with open(fpath, "r") as F:
            Data = json.load(F)
            Create_a_MadLib = cls(**Data)
        return Create_a_MadLib      

    def Get__The__Words__From__TheUser(self):
        print("Please enter the words that you want: ")
        for desc in self.Word_Desc:
            UI = input(desc + " ")
            self.UserInput.append(UI)
        return self.UserInput


    def Build__A__Story(self, Word):
        self.Story = self.Temp.format(*self.UserInput)
        return self.Story
        
    def Display_A_MadLib_Story(self):
        print(Story)
    
    def Choose_A_MadLib_Temp():
        print("Please choose the Mad Lib that you want from the list:")
        MadLibGen = os.listdir(CreateaMadLib.path)
        Temp = input(str(MadLibGen) + " ")
        return Temp
        
        Temp_Name = Choose_A_MadLib_Temp()
        #Temp_Name = "ArcadeMadLib.json"
        Create_a_MadLib = CreateaMadLib.Get__From__Json(Temp_Name)
        Word = Create_a_MadLib.Get__The__Words__From__TheUser()
        Story = Create_a_MadLib.Build__A__Story()
        Create_a_MadLib.Display_A_MadLib_Story()

更新:我用 Path = 'C:/MadLibGen' 替换了 Path = "./MadLibGen",运行它时出现空白屏幕。这不正确吗?

标签: python

解决方案


首先,如果你在 windows 上,你应该使用 windows 样式的路径:

Path = 'c:\\MadLibGen'

其次,您经常遇到变量名大写错误的问题,这会导致您的代码崩溃:

if not Path:
    Path = cls.path

但是cls没有会员path它有一个Path大写P的会员!

同样在这里:

MadLibGen = os.listdir(CreateaMadLib.path)

它应该是:

MadLibGen = os.listdir(CreateaMadLib.Path)

最后,您发布的代码是否完整?
它似乎缺乏调用逻辑——创建类和调用任何方法的代码。

看起来你错过了类似的东西:

if __name__ == '__main__':
    madlib = CreateMadLib()
    # call methods

添加后,您将收到更多错误消息,例如此方法:

def Display_A_MadLib_Story(self):
    print(Story)

应该是:

def Display_A_MadLib_Story(self):
    print(self.Story)

并且可能需要有一些逻辑来检查self.Story不是None


推荐阅读