Importing files from different directory — Python

Well, got stumbled by importing python files from different folders while writing a script. Here are the different methods we can use to import python files. We are using this file structure for the example:

medium??? importing_files_python??? method_1? ??? equation_eval? ? ??? assignment1.py? ??? operations? ??? addition.py? ??? subtraction.py

0. Using sys.path

According to python docs, sys module provides access to some variables used or maintained by interpreter and functions that interact strongly with interpreter. It is always available.

Solution 0:

This is because python looks for files in a script?s current directory only. Hence, we need to tell python to look at other directories as well if not found in the current directory. This possible path to look for file is done using sys.path.insert(index, ‘path/to/file’) method.

So by doing

import syssys.path.insert(1, ‘/Users/dichha/Projects/medium/importing_files_python/method_1/operations’)from addition import addfrom subtraction import subtract

we can successfully run assignment1.py file which uses add and subtract methods.

For sanity check, do

print(sys.path)

to see if a desired directory?s path is present in the sys.path variable.

Look that we are inserting at index 1.

On digging deeper into sys.path’s type, it belongs to class list! Makes sense, has List like methods. ?

  1. Using PYTHONPATH environment variable

Solution 1:

Put the operation directory in PYTHONPATH environment variable. In Mac OS, you can use following cli.

export PYTHONPATH=$PYTHONPATH:/Users/dichha/Projects/medium/importing_files_python/method_1/operations

For sanity check, you can do

echo $PYTHONPATH

to see if a desired directory?s path is present in the environment variable.

So your import would be just this:

from addition import addfrom subtraction import subtract

An example code of the tutorial is here. For your next understanding level, you could import a class. Ehhh.. the example code also has this solution. ?

Hope, this solves your issue. ?

2

No Responses

Write a response