Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

ImportError on tilde path

📅 2017-Sep-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

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