ImportError on tilde path

Problem

I had a Python module named foobar.py located inside ~/foobar directory. To be able to import it, I did this in my Python code:

import sys
sys.path.append("~/foobar")
import foobar

However, when that script was run, it gave this error:

Traceback (most recent call last):
  File "./hello_world.py", line 10, in 
    import foobar
ImportError: No module named foobar

Solution

It turns out that Python cannot expand the tilde to my home directory! This was quite surprising to me. Once I expanded it to the absolute path, the import worked fine.

Tried with: Python 2.7.12 and Ubuntu 16.04

Advertisements

2 thoughts on “ImportError on tilde path

  1. Small precision for the unaware reader (as I was few time ago) : «expand to the absolute path» means :
    os.path.expanduser(“~/foobar.py”)

    In my scripts I quite often initiate with
    HOME=os.path.expanduser(“~”)
    and then use os.path.join(HOME, )

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s