Python:在其他模块中使用的类中打开时的文件位置

2024-10-03 02:46:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一个文件结构:

test
    mammals
        Wolf.py
        wolfname.txt
    Zoo.py

Wolf.py里面我有:

class Wolf:
    def __init__(self):
        with open('wolfname.txt', 'r') as fileobj:
            self.name = fileobj.read()
        print(self.name)

wolf = Wolf()

如果我从内部调用它Wolf.py,它工作得很好。如果我从Zoo.py内部调用它,它会给出一个FFileNotFoundError: [Errno 2] No such file or directory: 'wolfname.txt' 错误。你知道吗

在不解析为绝对路径的情况下修复它的方法是什么?将来我可能还想使用其他新包中的Wolf类。你知道吗

我在动物园里使用这个导入:

from mammals.Wolf import Wolf

wolf = Wolf()

编辑:我做了这个复制在线显示:https://repl.it/repls/DrearyGrizzledMicroscope


Tags: 文件namepytestselftxtdef结构
3条回答

我用这个:

class Wolf:
    def __init__(self, path = ''):
        with open(path + 'wolfname.txt', 'r') as fileobj:
            self.name = fileobj.read()
        print(self.name)

在动物园里:

from mammals import Wolf

print("inside Main.py")
wolf = Wolf.Wolf("mammals/")

因此,在不同的文件中,我可以传递不同的相对路径。你知道吗

尝试重命名'狼.py'文件或Wolf类名。你知道吗

它可能会解决FileNotFoundError,因为名称是相同的。你知道吗

否则:也许this answer会帮到你?你知道吗

而不是那样做;这样做:

from mammals import Wolf

然后可以通过Wolf.Wolf访问Wolf类

相关问题 更多 >