Python import module parent directory

how to import module from parent directory in python in 2022?

There are multiple packages already in the python packages which are loaded in Python by default. Sometimes it is essential to know how to import module from parent directory in python in order to use particular methods and features that might not be available in Python by default. This is generally used by people in an organization where particular techniques that are exclusive to be used by the organization members are shared with the team members.

In this article, we’ll see how to import module from parent directory in python and go about multiple methods to do the same and any hacks that are possible to work our way around the same.

What is a module in Python?

A module is a small Python file that contains some python code and has statements and definitions within it. The file itself can be called with a module name with a .py extension. The file can have some exclusive code that you can use to make your analysis simpler. The code breakdown into smaller parts can help a python programmer take their efforts into the analysis without having to repeat the entire basic definitions of the code that can be imputed from another module in python.

Читайте также:  Document

how to import module from parent directory in python in 2022?

Modules are generally imported using the import keyword in python, which can be used within a statement to import modules that are predefined in Python or another module that exists in the parent directory as you will see in the section titled, “How to import module from parent directory in Python?”

Check out this link to understand more: Modules in Python explained

What is a Parent Directory in Python? (and for coding languages in general)

A directory can be considered to be a storage area or a vault with multiple layers within it. The parent directory is the outermost layer that encompasses all the layers within it and the layers inside it are other directories within the parent directory. The working directory is where the programming language currently is executing commands and the general default working directory is at the path of installation in the system.

Check out the article mentioned at the beginning of this article to understand how you can change your working directory in Python.

How to import module from parent directory in Python?

Let us go over three methods that you can use to import a module from the parent directory in Python. Feel free to use any of the mentioned codes and copy them as required. These are pulled from resources like StackOverflow and Python docs to help you find the different methods in one single place.

Method 1

sys.path.append()

The first and foremost method which you can use is to add the file path as an argument in the sys.path.append() function which will add the parent directory into the default workspace or the PYTHONPATH of your python environment and you can then import your required modules from there without any problem. This is by far, the simplest method to retrieve or import module from parent directory in python.

Find an example execution of the code here:

import sys # appending the parent directory path sys.path.append('parent directory path here') # importing the methods from parentdirectory.parent_module import parent_directory_method parent_directory_method()

and now you can use the methods in your environment with the parent directory being appended using the sys.path command.

Method 2

When you don’t know what the file path to your parent directory is, then you can make use of the os library in python and get the path of your current working directory and then check the directory name using the os library and continue on with replacing the file path with the variable containing the output from the os library i.e. parent_directory in this case and import the required module from the parent directory.

import sys import os current = os.path.dirname(os.path.realpath(__file__)) parent_directory = os.path.dirname(current) sys.path.append(parent_directory) from parentdirectory.parent_module import parent_directory_method parent_directory_method()

Method 3

Another simple way is to use the sys.path.insert along with the os library’s abspath command which looks like this:

import os, sys parent = os.path.abspath('.') sys.path.insert(1, parent) import parent_directory_module

Using the parent directory with the ‘.’ as done in the Command Line Prompt or the Anaconda prompt can help you with the os.path.abspath code to retrieve the parent directory to work with. The parent directory’s path is then inserted using the sys.path.insert code into the PYTHONPATH environment and thereby allowing you to work with the modules in your parent directory as and how required. Check out this YouTube video if you think a video tutorial with the same can help you better.

Krish Naik is one of the best data science tutors out there and in this video, he explains how you can work around Python and import modules in different directories in your python environment in an easy way. The directories are created from scratch and is easier to understand in the video tutorial and better to follow along with.

Conclusion

Generally, most data scientists today have a pre-prepared format of analysis procedure to follow in their projects. Such lines of code generally fall under the category of the EDA or Exploratory Data Analysis. Having a module named eda.py can speed up such time-taking processes by letting data scientists focus more on the outcome of the code and avoid repetitiveness of tasks that can be cloned from another project.

It is in these cases that the requirement to understand how to import modules from parent directory in python comes into the picture and is essential for data scientists to know, in order to ensure that the modules that are prepared in advance for such scenarios find their way to the projects and save time and efforts.

Try importing a module from your own parent directory into your projects and let us know if you think there is a better method for “How to import module from parent directory in Python?in the comments below!

For more such content, check out our website -> Buggy Programmer

Источник

Import Modules From Parent Directory in Python

Import Modules From Parent Directory in Python

  1. Import a Module From the Parent Directory in Python Using the Relative Import
  2. Import a Module From the Parent Directory in Python by Adding It to PYTHONPATH
  3. Import a Module From the Parent Directory in Python Using the sys.path.insert() Method

This tutorial will explain various methods to import a module from the parent directory in Python. We import different modules to use other functionalities in our code. It saves us from copying or implementing the functionalities again and makes the code clean and easier to understand.

Suppose we want to import a module from the parent directory of the current project directory. We can do so using different methods, which are explained below.

Import a Module From the Parent Directory in Python Using the Relative Import

The relative import is used to import a module in the code using the current directory path as a reference. To import a module using the import statement, we will first have to declare the directory a package by adding the __init__.py file in the parent directory. Once the parent directory is declared a package, we can import the module using the relative package approach.

Suppose we have the following directory tree.

parent_parent_directory/  parent_directory/  mymodule.py  __init__.py  current_directory/  currentmodule.py  mymodule.py  __init__.py 

The below example code demonstrates how to import the module from the parent package.

from ..parent_directory import mymodule 

To import the module from the directory two levels above from the current directory, we will have to put three dots before the package directory name to go two levels back, as shown in the below example code.

from . parent_parent_directory import mymodule 

Import a Module From the Parent Directory in Python by Adding It to PYTHONPATH

The PYTHONPATH is an environment variable specifying the directories list that Python should look to import modules and packages.

So if we add the parent directory from where we need to import the module, Python will automatically look into the parent directory and find the required module.

Import a Module From the Parent Directory in Python Using the sys.path.insert() Method

We can also use the sys.path.insert() method to add the parent directory to the sys.path list, which is the list of strings that specifies the paths to look for the packages and modules. The sys.path contains the PYTHONPATH environment variable directory list, and other paths can also be added using the sys.path.insert() method.

The below example code demonstrates how to use the sys.path.insert() method to add the parent directory to the sys.path list in Python.

import os, sys  p = os.path.abspath('.') sys.path.insert(1, p)  import mymodule 

Related Article — Python Import

Источник

How to Import File from Parent Directory in Python? (with code)

How to Import File from Parent Directory in Python? (with code)

Working on a lengthy project with a lot of recurring functionalities? Looking for a simple method to modify your code? Your issues can be resolved because Python is a dynamically large language that gives you plenty of options for customizing and condensing your lengthy codes.

Utilizing the split and code features, i.e. For each function you need to use, you can create a separate file and then just call the function ‘n’ times in your main code. All files must be in the same parent directory, and that is the only consideration. In this article, we will learn how to import modules or files from the parent directory.

How to Import Files from the Parent Directory in Python?

Yes, you can import things from the parent directory in Python. This can be achieved using the following method.

You can create the function that you will later need to import when creating the program in an empty file, then save the file with the extension «.py». The Python file will now be converted into a Python module, which you can then import into any other file by simply executing the command «import ‘filename'». Just remember that both files need to be in the same directory.

python parent directory

As you can see, we have a my_function.py file that contains a print statement. When we import it into a fresh Jupyter notebook, it simply returns the output «Hello,» indicating that the module has been imported properly. But there are more methods as well.

The best way to import files from the parent directory in Python is by using the sys module. The sys module offers access to several variables that the interpreter uses or maintains, as well as to functions that have close relationships with the interpreter.

The path variable, which is a list of strings that provides the search path for modules, is one of these functions. You can import files and modules from the parent directory by adding the path of the parent directory to this list.

Either you can import from parent directory using sys.append() method, as shown below:

import sys sys.path.append('..') from Favtutor import my_function

Here, we’ve used the append() function to add the parent directory path to the system path before importing the ‘my_function.py’ file.

Or you can import from the parent directory using os.path.abspath() method, with the following code:

import os.path import sys # directory reach directory = os.path.dirname(os.path.abspath("__file__")) # setting path sys.path.append(os.path.dirname(os.path.dirname(directory))) # importing from Favtutor import my_function my_function
module 'Favtutor.my_function' from 'f:\\projects\\Favtutor\\..\\Favtutor\\my_function.py'> 

In order for Python to locate and import the my_function function from the Favtutor module, this code adds the parent directory of the current file to the Python path.

The code is broken down as follows:

  1. Add the sys and os.path modules.
  2. Using os.path.dirname(os.path.abspath(«__file__»)), set directory to the parent directory of the currently open file.
  3. Using sys.path, add the parent directory to the Python path.append(os.path.dirname(os.path.dirname(directory))).
  4. Use the from Favtutor import my_function command to import the my_function function from the Favtutor module.
  5. Use my_function to invoke the my_function function.

Python 3 and Python 2 both allow for the import of files and modules from the parent directory.

If you still have any doubts, you can chat with our online python tutors to understand this better.

Conclusion

In conclusion, using the sys module, it is feasible to import files and modules from the parent directory in Python. These methods make managing complex projects in Python with many subdirectories simple. Happy Learning 🙂

Источник

Оцените статью