1

My folder trees:

./
├── README.MD
├── basic
│   └── thresh.py
├── images
│   └── figure.jpg
└── utils
    ├── util.py
    └── util.pyc

I want to import util.py in thresh.py:

import sys
sys.path.append('../utils')
import util

When I run command $ python thresh.py in the basic folder, it's allright. But run $ python ./basic/thresh.py in the topmost folder, I will get the error:

ImportError: No module named util

So how to make $ python ./basic/thresh.py and $ python thresh.py both work to import file by given the file's relative path to executed file regardless of python command path?

1 Answer 1

1

You can get the absolute path of the script you are executing with (there are other variants also using __file__, but this should work)

import os
wk_dir = os.path.dirname(os.path.realpath('__file__'))
print( wk_dir )

and then get your dir with it, e.g.

import sys
sys.path.append(wk_dir+'/../utils')

PS: You might need to use __file__ instead of '__file__'.

Sign up to request clarification or add additional context in comments.

3 Comments

This work. But you need change '__file__' to __file__ in your code.
@tomfriwel - The code posted was tested and it works. I found it somehwere else too. The change you suggest does not work for me, although I have seen other posts using it similarly. I did not explore this in detail, but the important points are: 1) you solved your problem, 2) others are aware that they might need to try both.
Maybe we use different version of Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.