parsecer
parsecer

Reputation: 5106

Python: file location when opened inside a class that is used in other modules

Suppose I have a file structure like this one:

test
    mammals
        Wolf.py
        wolfname.txt
    Zoo.py

And inside Wolf.py I have:

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

wolf = Wolf()

If I call it from inside Wolf.py, it works fine. If I call it from inside Zoo.py, it gives a FFileNotFoundError: [Errno 2] No such file or directory: 'wolfname.txt' error.

What is the way to fix it without resolving to absolute paths? I might want to use the Wolf class from some other new package in the future as well.

I use this import inside the Zoo:

from mammals.Wolf import Wolf

wolf = Wolf()

EDIT: I've made this repl.it to show it online: https://repl.it/repls/DrearyGrizzledMicroscope

Upvotes: 0

Views: 91

Answers (3)

parsecer
parsecer

Reputation: 5106

I resorted to using this:

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

and in Zoo:

from mammals import Wolf

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

Thus in different files I can pass different relative paths.

Upvotes: 0

Vicrobot
Vicrobot

Reputation: 3988

Instead of that; do this:

from mammals import Wolf

Then you can access Wolf class by Wolf.Wolf

Upvotes: 1

JaFizz
JaFizz

Reputation: 356

Try renaming the 'wolf.py' file or Wolf classname into something else.

It will maybe solve the FileNotFoundError because the names are the same.

Otherwise: maybe this answer will help you out?

Upvotes: 0

Related Questions