How do I import a Python file?

Sorry, this is definitely a duplicate, but I cannot find the answer. I am working in Python 3 and this is the structure of my application:

/home
  common.py
  australia/
    new-south-wales/
      fetch.py

      

I got into the directory home/

by running fetch.py

. How do I import functions from common.py

within a script?

I installed fetch.py

as follows:

from common import writeFile

      

But I am getting the following error:

File "australia/new-south-wales/fetch.py", line 8, in <module>
    from common import writeFile
ModuleNotFoundError: No module named 'common'

      

If I just do python -c "from common import writeFile"

, I don't see the error.

Does the interpreter have to look in the current directory for modules ?

+3


source to share


2 answers


before importing your directories to be imported must have a file __init__.py

in this folder

#solution 1 (import at runtime)

To import a specific Python file into "runtime" with a known name:

import os
import sys
script_dir = "/path/to/your/code/directory"

# Add the absolute directory  path containing your
# module to the Python path

sys.path.append(os.path.abspath(script_dir))

import filename

      

#solution 2 (add files to one of the python libraries)

since you have a shared library you can run



>>> import sys
>>> print sys.path

      

and see what directories you can put your code in and use in each project. You can move your shared package to one of these directories and treat it like a regular package. For example for common.py if you put it in one root directory of one of these directories you can import asimport common

#solution 3 (use relative imports)

# from two parent above current directory import common
# every dot for one parent directory
from ... import common 

      

and then change to parent directory and run

python -m home.australia.new-south-wales.fetch

      

+5


source


From the description, I am assuming that you are not running this package as a complete python package, as separate files.

What you can do is use full modules. This means adding empty __init__.py

to directories with your code. You will also need to change the name new-south-wales

to new_south_wales

, as it must be a valid module name.

Assuming home

is the name of your application, you should:

home/
  __init__.py
  common.py
  australia/
    __init__.py
    new_south_wales/
      __init__.py
      fetch.py

      

Next, you need to run the script for your application - this means something simple:



#!/usr/bin/env python
from australia.new_south_wales import fetch
fetch.your_main_function()

      

Or you can add setup.py

with a complete package description. If you provide entry points and the script is automatically generated.

Now when you start your code in the context of a package, yours fetch.py

can do:

from ..common import writeFile

      

+1


source







All Articles