Need help referencing Python Package when the filename consists of a period key

0 votes

Hi all,

I have a pretty simple question. I am making use of Django and I have a file which is called models.admin.py 

Check out the below syntax, this is what I want to do:

from "models.admin" import *

Maybe it is because of the double quotes that I use - I am ending up with a beautiful error message. 

But consider the following case:

from models.admin import *

If I end up doing that then I get another error! This time it is the ImportError: No module named admin"

My question is basically this - Is there any way to import a file in Python which consists of a period in the name?

All help appreciated!

Jan 25 in Python by Anirudh
• 2,060 points
29 views

1 answer to this question.

0 votes

Hi, it's a very simple answer actually. 

You can make sure to import a module with a name which is not valid. Make sure you use imp for this purpose.

Let me give you an example:

Let us say you are assuming the file is called as models.admin.py then you can consider doing this:

import imp
with open('models.admin.py', 'rb') as fp:
    models_admin = imp.load_module(
        'models_admin', fp, 'models.admin.py',
        ('.py', 'rb', imp.PY_SOURCE)
    )

Also, make sure to glance at the official documentation on the imp.find_module and imp.load_module just before you go about implementing it.

Hope this helped!

answered Jan 25 by Nymeria
• 3,500 points

Related Questions In Python

0 votes
1 answer

Need help writing a dataframe into a csv with the help of a loop

Using the following logic you can arrive ...READ MORE

answered Apr 17, 2018 in Python by anonymous
777 views
+1 vote
4 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
141 views
0 votes
1 answer

Obtaining a value when given a key in python dicionaries

We cannot. Dictionaries aren't meant to be ...READ MORE

answered May 31, 2018 in Python by Nietzsche's daemon
• 4,260 points
22 views
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
78 views
0 votes
1 answer
0 votes
1 answer

Need help with making use of Pluck in Python

Hi, good question. Easy solution to be ...READ MORE

answered Jan 24 in Python by Nymeria
• 3,500 points
58 views
0 votes
1 answer
0 votes
1 answer