Ambika Saxena
Ambika Saxena

Reputation: 215

Importing modules from different folder python for unknown path

I have been working on a python project and I am new to it. I have made a small library for my project in which I have several different modules doing different tasks.

For example: I have 5 modules namely add, subtract, multiply, divide and root. I call all these .pyc files into my main.py file and my code runs properly if all of them are in the same folder.

Now, I want to store my main.py at: D:\project\main.py and these 5 .pyc files at : D:\project\Lib\ (In the Lib folder)

I found a solution as to mention the path of the folder Lib into the code but I can not do so as I need to submit the code somewhere and if they try to run this on their PC, it might not import these files.

What would be the possible solution to this?

Upvotes: 1

Views: 3020

Answers (2)

Oleksii Filonenko
Oleksii Filonenko

Reputation: 1653

Try creating a package.

Use a directory structure like this:

.
+-- main.py
+-- lib
    +-- __init__.py
    +-- add.pyc
    +-- substract.pyc
    +-- ...

Then, in your main.py file, you can import them like this:

from lib import add

More on packages on Python docs

Upvotes: 2

anekix
anekix

Reputation: 2563

Inside D:\project\Lib create an __init__.py file. and put all your modules in D:\project\Lib now lib works as a python package.you dir structure should now look like this:

D:\project\Lib
           |
           +--- __init__.py
           +--- add.py
           +--- sub.py
           +--- multiply.py

Now from any file inside (say for ex main.py) D:\project call any module you want like this.

from Lib.add import something.

final dir structure will roughly look like this.

D:\project
        |
        +-- main.py
        +-- Lib
              |
              +--- __init__.py
              +--- add.py
              +--- sub.py
              +--- multiply.py

Upvotes: 1

Related Questions