A few functions about Python path

I was looking at the settings.py file of a Django project and it turned out there is a line of code likes this:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

It basically created variable called BASE_DIR pointing to the project directory.

__file__: the name of the running script, won’t exist in shell

os.path.abspath: the absolute path of the given file by joining current working directory and file name

os.path.dirname: the directory name of the absolute path,  = os.path.split(path)[0]

The os.path.join is pretty intelligent:

“Join one or more path components intelligently. The return value is the concatenation of pathand any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.”

>>> os.path.join(‘Users’, ‘a59347’, ‘Desktop’)
>>> os.path.join(‘Users’, ‘/Users/a59347’, ‘Desktop’)
>>> os.path.join(‘Users’, ‘/Users1/a59347’, ‘Desktop’)

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 )

Connecting to %s