Joe Allen
Joe Allen

Reputation: 389

Using file paths in import statements python

I have the file structure of:

mainprogram.py
/Scripts
    Data.py

where the file Data.py is in the folder Scripts, and contains a set of functions and mainprogram.py is trying to import those functions.

If Data.py was in the same folder as the file mainprogram.py, then I could simply write from Data import * and i would have all the defined functions from the file.

However, i always get the error: ModuleNotFoundError: No module named '__main__.Scripts'; '__main__' is not a package if I try to import it from the Scripts folder.

I have tried various methods including: from .Scripts.Data import * and from \\Scripts\\Data import *

Am I missing something, or is there a better way to import Data.py from a sub-folder?

Upvotes: 1

Views: 49

Answers (1)

serv-inc
serv-inc

Reputation: 38297

Have a look at https://docs.python.org/2/tutorial/modules.html:

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.

You need a __init__.py file (empty) in your Scripts folder. Then, you should be able to import Scripts.Data.

Upvotes: 2

Related Questions