假设我有这样一个文件结构:
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
我用这个:
在动物园里:
因此,在不同的文件中,我可以传递不同的相对路径。你知道吗
尝试重命名'狼.py'文件或Wolf类名。你知道吗
它可能会解决
FileNotFoundError
,因为名称是相同的。你知道吗否则:也许this answer会帮到你?你知道吗
而不是那样做;这样做:
然后可以通过
Wolf.Wolf
访问Wolf类相关问题 更多 >
编程相关推荐