Problem revisit: https://gist.github.com/tsaoyu/791d6c20962dbcc552eb29de725b3878
Suppose we have a standard Python project with following structure:
├── core.py ├── docs │ └── doc ├── example ├── resources │ ├── solar │ │ ├── Data │ │ │ └── global_radiation │ │ ├── SSEsolar.py │ │ ├── SSEsolarworking.py │ │ ├── __init__.py │ └── wind │ └── Data │ └── 10yr_wspd50m └── tests ├── __init__.py └── test.py
SSEsolar.py is a simple script that can read and then process solar radiation data from
filename = './Data/global_radiation' current_path = os.path.abspath(os.path.dirname('__file__')) file_path = os.path.join(current_path,filename) with open(file_path) as f: data = f.readlines()
This script works fine if you are running it exactly at it's own location. But it breaks as soon as you import
SSEsolar.py in other place. Let's say
core.py at package root,
import resources.solar.SSEsolar as SSEsolar and it will throw an error that
current_path is not defined. Why this didn't work when the script used anywhere else?
current_path = os.path.abspath(os.path.dirname('__file__')) # is the same as current_path = os.path.abspath(os.path.dirname('')) # which have the same effect as current_path = os.getcwd()
What we should use in python to get the absolute path of script is:
current_path = os.path.abspath(os.path.dirname(__file__))
But this do not works on iteractive shell, you may use non-iteractive way to run this.