1798

I have the following folder structure.

application
├── app
│   └── folder
│       └── file.py
└── app2
    └── some_folder
        └── some_file.py

I want to import some functions from file.py in some_file.py.

I've tried

from application.app.folder.file import func_name

and some other various attempts but so far I couldn't manage to import properly. How can I do this?

johan
  • 1,073
  • 1
  • 11
  • 22
Ivan
  • 21,917
  • 6
  • 22
  • 21
  • 2
    Related: http://stackoverflow.com/q/43476403/674039 – wim Apr 18 '17 at 15:56
  • Reading the official documentation helped me a lot! https://docs.python.org/3/reference/import.html#package-relative-imports – Kavin Raju S May 14 '20 at 01:20
  • If you have a dash in the name of the subfolder, it SHOULD BE UNDERSCORE. For example my-package and inside you have my_app folder and tests folder. If my_app is named my-app, you will have import problems – Gonzalo Apr 28 '21 at 15:01

31 Answers31

1768

Note: This answer was intended for a very specific question. For most programmers coming here from a search engine, this is not the answer you are looking for. Typically you would structure your files into packages (see other answers) instead of modifying the search path.


By default, you can't. When importing a file, Python only searches the directory that the entry-point script is running from and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

However, you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file
Cameron
  • 86,330
  • 19
  • 177
  • 216
  • 437
    `sys.path.append('/path/to/application/app/folder')` is cleaner imo – pseudosudo Sep 01 '11 at 21:48
  • 444
    @pseudosudo: Yep, it is, but inserting it at the beginning has the benefit of guaranteeing that the path is searched before others (even built-in ones) in the case of naming conflicts. – Cameron Sep 02 '11 at 02:47
  • 1
    Now if only Python `lists` had a `prepend` method so that the best choice wouldn't be ugly looking. I understand the reason why `prepend` doesn't exist (because it would have worse run times than `append`), but it seems to be a moot reason. Shouldn't easy to read be valued over quick to run? – ArtOfWarfare Oct 31 '13 at 18:54
  • @ArtOfWarfare deques solve the runtime issue, and they have an appendleft method. If you need a list, use a list, if you need a deque, use a deque. – kreativitea Nov 03 '13 at 18:34
  • 9
    @kreativitea - `sys.path` returns a `list`, not a `deque`, and it'd be silly to convert the `list` to a `deque` and back. – ArtOfWarfare Nov 03 '13 at 20:35
  • 42
    Is it considered as a pythonic way to manage .py files in folders? I'm wondering... why it's not supported by default? it doesn't make sense to maintain all .py files in a single directory.. – Ofir Sep 20 '15 at 18:32
  • 56
    @Ofir: No, this isn't a nice clean pythonic solution. In general, you should be using packages (which are based on directory trees). This answer was specific to the question asked, and for some reason continues to accrue a large number upvotes. – Cameron Sep 21 '15 at 02:38
  • 2
    @Cameron What exactly is "the directory that the entry-point script is running from" mean? Thanks! – AdjunctProfessorFalcon Aug 20 '16 at 23:11
  • 2
    @Malvin9000 That means that if the file you are working on is not the main file for the program. For example say you are working on a module named `foo` and you want it imports a package named `bar`. Now if you write another script, `spam` that imports `foo` then `spam` is the entry-point script, and that when `foo` calls `import bar` python will search in `foo`'s directory and then the directory containing `spam`. – calder.ty Aug 21 '16 at 19:58
  • 2
    I already have the path in sys.path. When I do `print(sys.path)` it shows me the path is there but when I try and import it still gives me the **ImportError**. Why could this be happening? – Haseeb Jun 10 '17 at 14:55
  • 2
    @Cameron: Could you then provide the clean pythonic way to do this, or a link to the solution? – rain_ Jun 20 '17 at 15:11
  • 1
    @rain_: Use [Python packages](https://docs.python.org/2/tutorial/modules.html#packages) as suggested by joey's answer. – Cameron Jun 20 '17 at 16:18
  • 2
    @Cameron. It does not work for me. Im using a project folder. with some subfolders on it. One of those subfolders containts an __init__.py and files.py which has functions on them. From any file in a subfolder I use: from functions_folder.functions import *, and it just doesnt work. – rain_ Jun 21 '17 at 09:43
  • @GabrielStaples yes, it does work on relative paths. – Andreas Forslöw Sep 24 '19 at 19:41
  • Another thing worth pointing out about this approach, which makes it non-pythonic, is that you cannot have the same name for any of your `sys.path` modules as one of your local modules. I.e. you cannot import `sys/path/module.py` to your `current/package/main.py` if `current/package/main.py` imports `current/package/module.py`. In other words, all the imported modules has to have unique names. – Andreas Forslöw Sep 24 '19 at 19:48
  • 1
    Terrible advice even for this specific question. Far better to update `PYTHONPATH` at the command line instead. – jpmc26 Oct 18 '19 at 03:15
  • 3
    This is terrible. What if I decide to refactor and move my package to a different directory? Do I need to find all files using that package and update that `sys.path.insert` statement? – alex Jan 30 '20 at 16:58
  • It's important to note that even if you use something like `os.path.abspath` aliases like `~` for your home directory are not replaced. – McLawrence Apr 23 '20 at 10:19
  • 1
    Interesting. It only takes a path as a string. It does not accept a path object. – Steve Scott Jun 12 '20 at 17:52
  • 1
    Doesn't work for me. I have a file `foo` which I import, which in turn imports `conftest`, which located at a `../conftest.py` file. So I do `sys.path.append(tests_dir)`, where `tests_dir` I tried to be both `../` and an absolute path. However upon executing `import foo` I still get "No module test named 'conftest'`. – Hi-Angel Jul 27 '20 at 09:43
  • @Hi-Angel , does this solve your problem?: https://stackoverflow.com/questions/62886769/is-it-possible-to-import-a-python-file-from-outside-the-directory-the-main-file – theX Aug 05 '20 at 01:19
  • @theX thanks, I should try it. For now I worked around this be placing the script in a different directory. – Hi-Angel Aug 05 '20 at 06:19
  • Python's approach related to module importation has a lot to improve yet. It could be simpler and straightforward like JavaScript, C#, Java, C++, and so on. – Rogério Oliveira Aug 26 '20 at 15:11
  • Hi guys, I have the same problem but the solution doesnt work. the path in the brackets is underlined and can't be find. What can I do? Its the correct path – Shalomi90 Sep 07 '20 at 15:13
  • 1
    @Shalomi11 On Windows, I recommend `sys.path.insert(1, os.path.abspath('/path/to/application/app/folder'))`, since with the notation above, the slashs are not how they should be in Windows. (You can check this if you put a breakpoint after this line and then in the debug mode, check "sys.path") – Isi Sep 25 '20 at 08:34
  • @Cameron Can you link to the pythonic solution you described, involving packages and directory trees? – young_souvlaki Mar 26 '21 at 17:59
930

Nothing wrong with:

from application.app.folder.file import func_name

Just make sure folder also contains an __init__.py, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH.

Ken Mueller
  • 2,126
  • 1
  • 15
  • 25
joey
  • 9,517
  • 1
  • 12
  • 8
  • 59
    Because this doesn't cover the cases where modifying `PYTHONPATH` is necessary. Say you have two folders on the same level: `A` and `B`. `A` has an `__init.py__`. Try importing something from `B` within `A`. – msvalkon Mar 06 '14 at 13:45
  • that's what i was looking for, ie works with standard local lib directory – zlr Apr 15 '14 at 11:48
  • 8
    this is a great answer - I was missing the __init__.py to initialize the package. Also encourages best practice so that there's less risk of namespace collision. Thanks! – sofly Nov 04 '14 at 20:20
  • 46
    What's inside the `init.py` or `__init__.py` file? – X.Creates May 09 '15 at 02:16
  • 61
    @Xinyang It can be an empty file. Its very existence tells Python to treat the directory as a package. – jay May 11 '15 at 23:24
  • 1
    `__init__.py` syntax is described in more detail in https://docs.python.org/3/tutorial/modules.html#packages and is useful if the package resides in a system or PYTHONPATH (sub-)dir or inside a dir of the calling application itself. – Ax3l Dec 06 '15 at 13:34
  • 22
    This is not currently the highest voted answer, but it IS the most correct answer (for most cases). Simply create a package. It's not hard. The other answers are needed because sometimes you might be restricted from certain system changes (creating or modifying a file, etc) like during testing. – Scott Prive Mar 03 '16 at 18:59
  • 2
    The empty __init__.py is vital in the container directory, thanks. – Sunding Wei Sep 12 '16 at 08:42
  • 10
    Of course this answer assumes that `application` and `app` are packages already (i.e. you already have `__init__.py` in both of them). As the result of adding `__init__.py` also to `folder`, `application.app.folder` becomes a (sub) *package*, from which you can access the *module* `application.app.folder.file`, whose symbol `func_name` can now be imported – Yibo Yang Apr 29 '17 at 07:12
  • 50
    Whatever I try, this won't work. I want to import from a "sibling" directory, so one up one down. All have __ init __.py's, including parent. Is this python 3 -specific? – dasWesen Jun 18 '17 at 12:54
  • 1
    @dasWesen, don't think it should differ much, but if this doesn't help you, ask a new one – borgr Oct 24 '17 at 11:57
  • 2
    @borgr I think I circumvented it back then... Sorry, I don't remember what code that problem was in, this was too long ago (and it's not relevant for me right now). But there seems to be a common issue, so if anyone else has the problem right now, yes, please go ahead and open a new question. – dasWesen Oct 30 '17 at 11:10
  • @msvalkon If changing the path to directory B won't break your program, you can use symbolic links along with this answer to solve that problem. Let's say you're in directory A and want to import something in directory B. Add `__init__.py` to directory B. Make a symbolic link of directory B; put it in directory A. In directory A, `import B.yourModule`. – Brōtsyorfuzthrāx Feb 22 '18 at 09:50
  • 1
    Is there a solution to this problem now? I can't find a way to circumvent the problem and I find it very confusing to have all files for one single program in one folder – SnitchingAuggie Jun 11 '18 at 21:55
  • This is the easiest solution – SMDC Jun 20 '18 at 06:31
  • 5
    running this script in command line with py3.7 on Windows gives me `No module named application.app.folder.file`. I have all the __init__.py in place including the one for the parent folder – kakyo Jun 07 '19 at 10:37
  • If my folder name is a_b_c and which contains app.py so how we can access it? @joey – Ashu Jul 29 '19 at 07:23
  • 2
    Is the `__init__.py` still required, given implicit package namespace? – Minh Nghĩa Nov 21 '19 at 15:41
  • 3
    i have folder `a/test.py` and the file `b.py` as the same level of a folder. even by adding a `__init__.py` file to the root folder (as side of `a` folder with `b.py`) i cant import a function from `b.py` file inside `test.py`... – a_m_dev Dec 17 '19 at 06:06
  • How would `application.app.folder.file` be changed in case there was a space in the name of the folder? Doesn't seem to be any clear answer to that. – Yeahprettymuch Jul 01 '20 at 10:56
  • 3
    This sounds like a joke. Many guys writing a lot of things about what is right and don't and finally someone says that is not "nothing wrong with"... – mpoletto Jul 06 '20 at 18:44
  • Wish Python 4 does something sensible about this so called Package system. No ,matter ow many `__init__.py` you put in place, python always fails to find modules. – pouya Dec 03 '20 at 17:55
  • 1
    Working and not working ... works when I try `from A.file import funcA` at level `Z` (folder that has A and B as sub-folder) at the IPython console. However, running `funcB` inside `B` folder that has `from A.file import funcA` fails and throws the error (ModuleNotFoundError: No module named 'FashionColor'). Note that running `funcB` will change the working directory to `B`. All folders have __init__.py. – Mohd Jan 19 '21 at 17:24
  • I am using python3, and it does not work for me – Lei_Bai Apr 14 '21 at 17:41
145

When modules are in parallel locations, as in the question:

application/app2/some_folder/some_file.py
application/app2/another_folder/another_file.py

This shorthand makes one module visible to the other:

import sys
sys.path.append('../')
slizb
  • 3,874
  • 3
  • 21
  • 22
  • 29
    As a caveat: This works so long as the importing script is run from its containing directory. Otherwise the parent directory of whatever other directory the script is run from will be appended to the path and the import will fail. – Carl Smith May 03 '17 at 03:02
  • 20
    To avoid that, we can get the parent directory of file `sys.path.append(os.path.dirname(os.path.abspath(__file__)))` – Rahul Sep 17 '18 at 10:09
  • That didn't work for me - I had to add an additional dirname in there to climb back up to the parent, so that running ```cli/foo.py``` from the command line was able to ```import cli.bar``` – RCross Jul 26 '19 at 11:23
  • 2
    @Rahul, your solution doesn't work for interactive shells – towi_parallelism Nov 27 '19 at 18:19
  • 3
    If you run it from your root folder (ie. application folder), you are probably fine with `sys.path.append('.')` then importing the module by using `from app2.some_folder.some_file import your_function`. Alternatively what works for me is running `python3 -m app2.another_folder.another_file` from root folder. – addicted Dec 16 '19 at 13:23
  • I find this to be the simplest way. just append the relative file path to the file containing the module you need. in my case: import sys sys.append('../data_structure/') . the module is in a file inside of the data_structure/ folder – Amir Dec 21 '19 at 18:47
93

First import sys in name-file.py

 import sys

Second append the folder path in name-file.py

sys.path.insert(0, '/the/folder/path/name-package/')

Third Make a blank file called __ init __.py in your subdirectory (this tells Python it is a package)

  • name-file.py
  • name-package
    • __ init __.py
    • name-module.py

Fourth import the module inside the folder in name-file.py

from name-package import name-module
Alex Montoya
  • 3,115
  • 19
  • 19
  • 9
    With name-folder being right below name-file.py, this should work even without the `sys.path.insert`-command. As such, the answer leaves the question, if this solution works even when name-folder is located in an arbitrary location. – Bastian Feb 01 '19 at 09:19
  • are you saying that I have to hardcode the path to the script? This means that the solution is not portable. Also the question is how to access from one subfolder to the other. Why not following the name convention and file structure of the original question? – Giacomo Mar 13 '21 at 18:40
65

I think an ad-hoc way would be to use the environment variable PYTHONPATH as described in the documentation: Python2, Python3

# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH

# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%
Ax3l
  • 1,392
  • 11
  • 20
  • Wait, would I replace myScripts with the filename? – Vladimir Putin Jun 29 '14 at 22:45
  • 6
    no, with the path of the directory to your .py file – Ax3l Jul 05 '14 at 13:57
  • 3
    Unfortunately, if you are using Anaconda, this won't work, since under the hood PYTHONPATH is not really used internally ! – information_interchange Apr 13 '20 at 01:28
  • 1
    For (recent) changes in anaconda, see this SO for workflows and comments for work-arounds: https://stackoverflow.com/questions/17386880/does-anaconda-create-a-separate-pythonpath-variable-for-each-new-environment Generally speaking, build and install small packages instead of hacking the import dirs. – Ax3l Apr 14 '20 at 08:53
55

Your problem is that Python is looking in the Python directory for this file and not finding it. You must specify that you are talking about the directory that you are in and not the Python one.

To do this you change this:

from application.app.folder.file import func_name

to this:

from .application.app.folder.file import func_name

By adding the dot you are saying look in this folder for the application folder instead of looking in the Python directory.

Billal Begueradj
  • 13,551
  • 37
  • 84
  • 109
CianB
  • 785
  • 6
  • 11
52

The answers here are lacking in clarity, this is tested on Python 3.6

With this folder structure:

main.py
|
---- myfolder/myfile.py

Where myfile.py has the content:

def myfunc():
    print('hello')

The import statement in main.py is:

from myfolder.myfile import myfunc
myfunc()

and this will print hello.

Billal Begueradj
  • 13,551
  • 37
  • 84
  • 109
danday74
  • 38,089
  • 29
  • 169
  • 214
38

From what I know, add an __init__.py file directly in the folder of the functions you want to import will do the job.

Berci
  • 424
  • 1
  • 4
  • 10
Vaibhav Singh
  • 399
  • 3
  • 2
  • 7
    only if the script that wants to include that other directory is already in the sys.path – Ax3l Feb 20 '16 at 16:53
  • 2
    I used `sys.path.append(tools_dir)` on Windows and I don't need to add a `__init__.py' file in my directory `tools_dir` – herve-guerin Mar 18 '17 at 12:42
32

In Python 3.4 and later, you can import from a source file directly (link to documentation). This is not the simplest solution, but I'm including this answer for completeness.

Here is an example. First, the file to be imported, named foo.py:

def announce():
    print("Imported!")

The code that imports the file above, inspired heavily by the example in the documentation:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

foo = module_from_file("foo", "/path/to/foo.py")

if __name__ == "__main__":
    print(foo)
    print(dir(foo))
    foo.announce()

The output:

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Note that the variable name, the module name, and the filename need not match. This code still works:

import importlib.util

def module_from_file(module_name, file_path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()

The output:

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Programmatically importing modules was introduced in Python 3.1 and gives you more control over how modules are imported. Refer to the documentation for more information.

wecsam
  • 2,261
  • 4
  • 21
  • 44
  • 15
    I don't know if anyone even tried to understand this, but I think that it's too complicated. – Dan Jan 07 '19 at 22:21
27

Worked for me in python3 on linux

import sys  
sys.path.append(pathToFolderContainingScripts)  
from scriptName import functionName #scriptName without .py extension  
dsg38
  • 467
  • 5
  • 8
27

I was faced with the same challenge, especially when importing multiple files, this is how I managed to overcome it.

import os, sys

from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))

from root_folder import file_name
Erick Mwazonga
  • 688
  • 9
  • 18
  • 4
    You answer would be more helpful if you could explain what it does differently from an ordinary import? – not2qubit Apr 23 '19 at 19:25
  • 1
    I had /path/dir1/__init__.py and /path/dir1/mod.py. For /path/some.py from dir1.mod import func worked. When in /path/dir2/some.py it only worked after I copied and pasted the above answer at the top of the file. Didn't want to edit my path since not every python project I have is in /path/. – jwal May 02 '19 at 11:52
26

Try Python's relative imports:

from ...app.folder.file import func_name

Every leading dot is another higher level in the hierarchy beginning with the current directory.


Problems? If this isn't working for you then you probably are getting bit by the many gotcha's relative imports has. Read answers and comments for more details: How to fix "Attempted relative import in non-package" even with __init__.py

Hint: have __init__.py at every directory level. You might need python -m application.app2.some_folder.some_file (leaving off .py) which you run from the top level directory or have that top level directory in your PYTHONPATH. Phew!

Zectbumo
  • 2,811
  • 26
  • 21
  • This doesn't seem to work if your directory's name starts with a number (e.g. `import ..70_foo.test` is not allowed) – secluded Oct 17 '20 at 11:19
23

Using sys.path.append with an absolute path is not ideal when moving the application to other environments. Using a relative path won't always work because the current working directory depends on how the script was invoked.

Since the application folder structure is fixed, we can use os.path to get the full path of the module we wish to import. For example, if this is the structure:

/home/me/application/app2/some_folder/vanilla.py
/home/me/application/app2/another_folder/mango.py

And let's say that you want to import the mango module. You could do the following in vanilla.py:

import sys, os.path
mango_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+ '/another_folder/')
sys.path.append(mango_dir)
import mango

Of course, you don't need the mango_dir variable.

To understand how this works look at this interactive session example:

>>> import os
>>> mydir = '/home/me/application/app2/some_folder'
>>> newdir = os.path.abspath(os.path.join(mydir, '..'))
>>> newdir
    '/home/me/application/app2'
>>> newdir = os.path.abspath(os.path.join(mydir, '..')) + '/another_folder'
>>> 
>>> newdir
'/home/me/application/app2/another_folder'
>>> 

And check the os.path documentation.

Also worth noting that dealing with multiple folders is made easier when using packages, as one can use dotted module names.

Nagev
  • 4,017
  • 1
  • 29
  • 35
21

Considering application as the root directory for your python project, create an empty __init__.py file in application, app and folder folders. Then in your some_file.py make changes as follows to get the definition of func_name:

import sys
sys.path.insert(0, r'/from/root/directory/application')

from application.app.folder.file import func_name ## You can also use '*' wildcard to import all the functions in file.py file.
func_name()
Chnossos
  • 8,332
  • 2
  • 22
  • 34
ChandanK
  • 491
  • 4
  • 10
14

This works for me on windows

# some_file.py on mainApp/app2 
import sys
sys.path.insert(0, sys.path[0]+'\\app2')

import some_file
Jim G.
  • 14,056
  • 19
  • 94
  • 153
Emeeus
  • 4,104
  • 2
  • 14
  • 32
14

In my case I had a class to import. My file looked like this:

# /opt/path/to/code/log_helper.py
class LogHelper:
    # stuff here

In my main file I included the code via:

import sys
sys.path.append("/opt/path/to/code/")
from log_helper import LogHelper
Walter
  • 118
  • 2
  • 12
schmudu
  • 1,821
  • 18
  • 28
11

I'm quite special : I use Python with Windows !

I just complete information : for both Windows and Linux, both relative and absolute path work into sys.path (I need relative paths because I use my scripts on the several PCs and under different main directories).

And when using Windows both \ and / can be used as separator for file names and of course you must double \ into Python strings,
some valid examples :

sys.path.append('c:\\tools\\mydir')
sys.path.append('..\\mytools')
sys.path.append('c:/tools/mydir')
sys.path.append('../mytools')

(note : I think that / is more convenient than \, event if it is less 'Windows-native' because it is Linux-compatible and simpler to write and copy to Windows explorer)

herve-guerin
  • 1,673
  • 12
  • 22
11

I bumped into the same question several times, so I would like to share my solution.

Python Version: 3.X

The following solution is for someone who develops your application in Python version 3.X because Python 2 is not supported since Jan/1/2020.

Project Structure

In python 3, you don't need __init__.py in your project subdirectory due to the Implicit Namespace Packages. See Is init.py not required for packages in Python 3.3+

Project 
├── main.py
├── .gitignore
|
├── a
|   └── file_a.py
|
└── b
    └── file_b.py

Problem Statement

In file_b.py, I would like to import a class A in file_a.py under the folder a.

Solutions

#1 A quick but dirty way

Without installing the package like you are currently developing a new project

Using the try catch to check if the errors. Code example:

import sys
try:
    # The insertion index should be 1 because index 0 is this file
    sys.path.insert(1, '/absolute/path/to/folder/a')  # the type of path is string
    # because the system path already have the absolute path to folder a
    # so it can recognize file_a.py while searching 
    from file_a import A
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

#2 Install your package

Once you installed your application (in this post, the tutorial of installation is not included)

You can simply

try:
    from __future__ import absolute_import
    # now it can reach class A of file_a.py in folder a 
    # by relative import
    from ..a.file_a import A  
except (ModuleNotFoundError, ImportError) as e:
    print("{} fileure".format(type(e)))
else:
    print("Import succeeded")

Happy coding!

WY Hsu
  • 1,400
  • 2
  • 18
  • 30
  • for more info about [absolute imports](https://stackoverflow.com/questions/42853617/python-fails-importing-package) – WY Hsu Jan 05 '20 at 09:36
  • 1
    your first proposed solution worked for me using sys.path.insert(1, '../a/') which I think is better than writing the full path. – Giacomo Mar 13 '21 at 18:49
  • In case someone has a local package that you would like to import instead of the system package (THAT HAS THE SAME NAME) please use sys.path.insert(1,'folder-to-grab-package-from') instead of sys.append('folder-to-grab-package-from') – MedoAlmasry Mar 15 '21 at 11:02
11

The best practice for creating a package can be running and accessing the other modules from a module like main_module.py at highest level directory.

This structure demonstrates you can use and access sub package, parent package, or same level packages and modules by using a top level directory file main_module.py.

Create and run these files and folders for testing:

 package/
    |
    |----- __init__.py (Empty file)
    |------- main_module.py (Contains: import subpackage_1.module_1)        
    |------- module_0.py (Contains: print('module_0 at parent directory, is imported'))
    |           
    |
    |------- subpackage_1/
    |           |
    |           |----- __init__.py (Empty file)
    |           |----- module_1.py (Contains: print('importing other modules from module_1...')
    |           |                             import module_0
    |           |                             import subpackage_2.module_2
    |           |                             import subpackage_1.sub_subpackage_3.module_3)
    |           |----- photo.png
    |           |
    |           |
    |           |----- sub_subpackage_3/
    |                        |
    |                        |----- __init__.py (Empty file)
    |                        |----- module_3.py (Contains: print('module_3 at sub directory, is imported')) 
    |
    |------- subpackage_2/
    |           |
    |           |----- __init__.py (Empty file)
    |           |----- module_2.py (Contains: print('module_2 at same level directory, is imported'))

Now run main_module.py

the output is

>>>'importing other modules from module_1...'
   'module_0 at parent directory, is imported'
   'module_2 at same level directory, is imported'
   'module_3 at sub directory, is imported'

Opening pictures and files note:

In a package structure if you want to access a photo, use absolute directory from highest level directory.

let's Suppose you are running main_module.py and you want to open photo.png inside module_1.py.

what module_1.py must contain is:

Correct:

image_path = 'subpackage_1/photo.png'
cv2.imread(image_path)

Wrong:

image_path = 'photo.png'
cv2.imread(image_path)

although module_1.py and photo.png are at same directory.

Mohsen Haddadi
  • 808
  • 2
  • 11
  • 17
7

If the purpose of loading a module from a specific path is to assist you during the development of a custom module, you can create a symbolic link in the same folder of the test script that points to the root of the custom module. This module reference will take precedence over any other modules installed of the same name for any script run in that folder.

I tested this on Linux but it should work in any modern OS that supports symbolic links.

One advantage to this approach is that you can you can point to a module that's sitting in your own local SVC branch working copy which can greatly simplify the development cycle time and reduce failure modes of managing different versions of the module.

Timothy C. Quinn
  • 2,184
  • 1
  • 24
  • 35
4

Instead of just doing an import ..., do this :

from <MySubFolder> import <MyFile>

MyFile is inside the MySubFolder.

Karthikeyan VK
  • 3,430
  • 3
  • 26
  • 39
3

I usually create a symlink to the module I want to import. The symlink makes sure Python interpreter can locate the module inside the current directory (the script you are importing the other module into); later on when your work is over, you can remove the symlink. Also, you should ignore symlinks in .gitignore, so that, you wouldn't accidentally commit symlinked modules to your repo. This approach lets you even successfully work with modules that are located parallel to the script you are executing.

ln -s ~/path/to/original/module/my_module ~/symlink/inside/the/destination/directory/my_module
picmate 涅
  • 3,317
  • 5
  • 38
  • 47
2

I was working on project a that I wanted users to install via pip install a with the following file list:

.
├── setup.py
├── MANIFEST.in
└── a
    ├── __init__.py
    ├── a.py
    └── b
        ├── __init__.py
        └── b.py

setup.py

from setuptools import setup

setup (
  name='a',
  version='0.0.1',
  packages=['a'],
  package_data={
    'a': ['b/*'],
  },
)

MANIFEST.in

recursive-include b *.*

a/init.py

from __future__ import absolute_import

from a.a import cats
import a.b

a/a.py

cats = 0

a/b/init.py

from __future__ import absolute_import

from a.b.b import dogs

a/b/b.py

dogs = 1

I installed the module by running the following from the directory with MANIFEST.in:

python setup.py install

Then, from a totally different location on my filesystem /moustache/armwrestle I was able to run:

import a
dir(a)

Which confirmed that a.cats indeed equalled 0 and a.b.dogs indeed equalled 1, as intended.

duhaime
  • 19,699
  • 8
  • 122
  • 154
2

You can use importlib to import modules where you want to import a module from a folder using a string like so:

import importlib

scriptName = 'Snake'

script = importlib.import_module('Scripts\\.%s' % scriptName)

This example has a main.py which is the above code then a folder called Scripts and then you can call whatever you need from this folder by changing the scriptName variable. You can then use script to reference to this module. such as if I have a function called Hello() in the Snake module you can run this function by doing so:

script.Hello()

I have tested this in Python 3.6

Dextron
  • 578
  • 4
  • 18
2

I've had these problems a number of times. I've come to this same page a lot. In my last problem I had to run the server from a fixed directory, but whenever debugging I wanted to run from different sub-directories.

import sys
sys.insert(1, /path) 

did NOT work for me because at different modules I had to read different *.csv files which were all in the same directory.

In the end, what worked for me was not pythonic, I guess, but:

I used a if __main__ on top of the module I wanted to debug, that is run from a different than usual path.

So:

# On top of the module, instead of on the bottom
import os
if __name__ == '__main__':
    os.chdir('/path/for/the/regularly/run/directory')
B Furtado
  • 1,193
  • 1
  • 17
  • 28
2

If you have multiple folders and sub folders, you can always import any class or module from the main directory.

For example: Tree structure of the project

Project 
├── main.py
├── .gitignore
|
├── src
     ├────model
     |    └── user_model.py
     |────controller
          └── user_controller.py

Now, if you want to import "UserModel" class from user_model.py in main.py file, you can do that using:

from src.model.user_model.py import UserModel

Also, you can import same class in user_controller.py file using same line:

from src.model.user_model.py import UserModel

Overall, you can give reference of main project directory to import classes and files in any python file inside Project directory.

kepy97
  • 680
  • 8
  • 12
  • do we need `__init__.py` under src to make this happen? – Richie F. Dec 17 '20 at 20:29
  • This is not an answer to the original question which was NOT about how to import from main.py, but rather (following your example) from user_model.py to user_controller.py. – Giacomo Mar 13 '21 at 18:38
2

The code below imports the Python script given by it's path, no matter where it is located, in a Python version-safe way:

def import_module_by_path(path):
    name = os.path.splitext(os.path.basename(path))[0]
    if sys.version_info[0] == 2:   
        # Python 2
        import imp
        return imp.load_source(name, path)
    elif sys.version_info[:2] <= (3, 4):  
        # Python 3, version <= 3.4
        from importlib.machinery import SourceFileLoader
        return SourceFileLoader(name, path).load_module()
    else:                            
        # Python 3, after 3.4
        import importlib.util
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod

I found this in the codebase of psutils, at line 1042 in psutils.test.__init__.py (most recent commit as of 09.10.2020).

Usage example:

script = "/home/username/Documents/some_script.py"
some_module = import_module_by_path(script)
print(some_module.foo())

Important caveat: The module will be treated as top-level; any relative imports from parent packages in it will fail.

Neinstein
  • 699
  • 1
  • 7
  • 28
2

In case anyone still looking for a solution. This worked for me.

Python adds the folder containing the script you launch to the PYTHONPATH, so if you run

python application/app2/some_folder/some_file.py

Only the folder application/app2/some_folder is added to the path (not the base dir that you're executing the command in). Instead, run your file as a module and add a __init__.py in your some_folder directory.

python -m application.app2.some_folder.some_file

This will add the base dir to the python path, and then classes will be accessible via a non-relative import.

Md Shafiul Islam
  • 1,090
  • 1
  • 8
  • 18
1

You can refresh the Python shell by pressing f5, or go to Run-> Run Module. This way you don't have to change the directory to read something from the file. Python will automatically change the directory. But if you want to work with different files from different directory in the Python Shell, then you can change the directory in sys, as Cameron said earlier.

IOstream
  • 103
  • 1
  • 6
1

So I had just right clicked on my IDE, and added a new folder and was wondering why I wasn't able to import from it. Later I realized I have to right click and create a Python Package, and not a classic file system folder. Or a post-mortem method being adding an __init__.py (which makes python treat the file system folder as a package) as mentioned in other answers. Adding this answer here just in case someone went this route.

mithunpaul
  • 2,559
  • 17
  • 18
0

Just use change dir function from os module:

os.chdir("Here new director")

than you can import normally More Info