Skip to content

Instantly share code, notes, and snippets.

@ChengLuFred
Last active October 25, 2020 22:46
Show Gist options
  • Save ChengLuFred/8fb4e8161641222ba2e88584a7761e55 to your computer and use it in GitHub Desktop.
Save ChengLuFred/8fb4e8161641222ba2e88584a7761e55 to your computer and use it in GitHub Desktop.
[Package Management in Python] smart way to import modules #Python

Import module from different file

import file_name as fn

or

from file_name import *

The file_name above is the name of your specific .py file under the same folder of your script.

Import module from different folder

from file_path.file_name import *

We link the file_path with file_name using . rather than /.

Import module from environment path

import sys
module_path = '/absolute/path/in/system'
sys.path.append(module_path)
from file_name import *

We can import sys at first, then add file path to system path environment in python.

However, we can simplify this process by adding your module path to environment permamentally

$ export PYTHONPATH=$PYTHONPATH:/absolute/path/in/system
$ python -c "import sys; print(sys.path)

The first line add your path to environment, and the second line check the path in your environment. After this, you may just import your package with only one line at beginning.

from file_path.file_name import *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment