1

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?

3
  • 1
    see about python packages. you need to convert a directory into a package by creating a file __init__.py in it. and then store all your modules and call it like from package.module import something Commented Jul 11, 2017 at 12:02
  • refer my answer below Commented Jul 11, 2017 at 12:10
  • 1
    also make sure you work with .py files instead of .pyc files. .pyc files will be generated by interprer for its internal purpose Commented Jul 11, 2017 at 12:17

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

@BrightOne. its not good idea to use .pyc fils directly rather they are generated by the python interpreter
@anekix OP used .pyc in the examples, it's not my own decision. Nonetheless, you are right.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.