3

I have a python file called

default.properties.py

How can I successfully import it as a module, I tried

import default.properties as prop

but it didn't work until I changed the name to default.py, Id like to keep the name with two extensions, is this possible?

user2798694
  • 1,023
  • 11
  • 26
  • See [here](http://stackoverflow.com/questions/1828127/how-to-reference-python-package-when-filename-contains-a-period) – kvorobiev Apr 08 '15 at 07:07
  • 1
    naming conventions highly advise against using periods in the filename, underscores instead should be used. i understand if this is someone else's module that you had no choice, just future reference – the_constant Apr 08 '15 at 07:15

2 Answers2

3

You can use imp

import imp
mymodule = imp.load_source('default.properties','default.properties.py')
>>>mymodule.variable
"i am variable in default.properties.py"

OR

mymodule = imp.load_module('default.properties',
                            open('default.properties.py'),
                            os.path.abspath('default.properties.py'),
                            ('.py', 'r', imp.PY_SOURCE))
>>>mymodule.variable
"i am variable in default.properties.py"    
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • In Python 3.1, it's `mymodule = importlib.machinery.SourceFileLoader('default.properties', 'default.properties.py').load_module()`. In Python 3.4, `load_module()` was deprecated. – 200_success Apr 08 '15 at 07:38
0

File names can only have one extension. Your file has extension py. The base name is default.properties.

You want to write

import default.properties

That is possible, but it requires that you make a package named default and a submodule of that package named properties.

Note that this involves making a directory named default containing files named __init__.py and properties.py.

You cannot import, using the import statement, a module in a file whose base name contains a period. That's because the file's base name must be a valid Python identifier.

In other words, you can't name your file default.properties.py but you can use the package mechanism to allow you to write

import default.properties
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490