Forums

import another python file

Hi,

I have a file abc.py and another file xyz.py . In the file xyz.py I want to use a function of abc.py so how do I import abc.py into xyz.py given assuming that they are in the same directory. What will be the import statement? I was trying:

import "absolute/path/to/the/file.py"

If they're in the same directory, then you need to use

from abc import functionname

This part of the official Python tutorial explains how import works.

When I import like this (as suggested), it works fine;

from school_info import function_name

The file on its own compiles without error but when I run my Django app in which this file is run I get the error in the browser:

ImportError at / No module named 'school_info'

How to correct this?

I figured out, I had to do this:

from . import school_info

and use the function like this:

school_info.function_name()

You can also do from .school_info import function_name

I'm guessing the problem with just the import abc was that you were running your python file without being in the working working directory. (eg: you are running /home/edmoneyball/yoursite/some_file.py and trying to import /home/edmoneyball/yoursite/school_info but the working directory was /home/edmoneyball)