Python3 import file from directory starting with number

Viewed 2059

I tried the answers in this question to no avail so I thought it'd be worth a separate question. The directory layout is as follows:

aale/
     2/
       2.py
       __init__.py
     3/
       3.py
       __init__.py
     __init__.py

The names are unfortunately unable to change (this is the layout given to us for a HW problem). I am trying to import 2 from 3 but it doesn't seem to be working. I tried using importlib as:

two = importlib.import_module('2.2') as well as two = importlib.import_module('2')

which didn't work also (gave a ModuleNotFoundError: No module named '2' error). Any help / other methods would be appreciated. I am using Python 3.6.

3 Answers

Assuming your script is in the aale directory, you will need to do your import like:

two = importlib.import_module('aale.2.2')

You can use __import__, i.e.:

two  = __import__("2.2") # or __import__("aale.2.2") 
three = __import__("3.3") # or __import__("aale.3.3")

Equivalent to:

import 2.2 as two  
import 3.3 as three

which isn't possible.


Notes:

  1. According to PEP 8 styling guide:

    Package and Module Names should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.

  2. I've tested the imports using the same folder structure as in your question and no errors were shown.

References:

  1. https://stackoverflow.com/a/16644280/797495
  2. In python, how to import filename starts with a number
  3. PEP 8 -- Style Guide for Python Code

You can use pathlib

It is basic:

from pathlib import Path


BASE_LOCATION = Path(__file__).parent

(You can add .parent to get to the folder above and so on.)

Edit

If this doesn't help you, you can try import weirdimport.

You can read more about this here.

Hope this helps!

Related