Importing files from different folder

I have the following folder structure.

application/app/folder/file.py

and I want to import some functions from file.py in another Python file which resides in

application/app2/some_folder/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?


By default, you can't. When importing a file, Python only searches the current directory, 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
sys.path.insert(0, '/path/to/application/app/folder')

import file

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.


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('../')
链接地址: http://www.djcxy.com/p/54820.html

上一篇: Python模块和Python包有什么区别?

下一篇: 从不同文件夹导入文件